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
sequencelengths
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
3a83ea274ee0db0d28aab2ab3ff5ec45
train_000.jsonl
1467219900
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?
256 megabytes
import java.util.*; public class LovelyPlandrome { public static void main (String[]args) { Scanner sc = new Scanner(System.in); String s = sc.next(); StringBuffer b = new StringBuffer(s); b.reverse(); System.out.print(s+b); } }
Java
["1", "10"]
1 second
["11", "1001"]
NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.
Java 8
standard input
[ "constructive algorithms", "math" ]
bcf75978c9ef6202293773cf533afadf
The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000).
1,000
Print the n-th even-length palindrome number.
standard output
PASSED
dc17d2866ed046c44a0085867dd440e6
train_000.jsonl
1467219900
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?
256 megabytes
import java.util.*; import java.lang.*; public class lovely{ public static void main(String[] args) { Scanner sc= new Scanner(System.in); String s=sc.nextLine(); String a=s; StringBuffer sb= new StringBuffer(s); sb.reverse(); System.out.print(a+sb); } }
Java
["1", "10"]
1 second
["11", "1001"]
NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.
Java 8
standard input
[ "constructive algorithms", "math" ]
bcf75978c9ef6202293773cf533afadf
The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000).
1,000
Print the n-th even-length palindrome number.
standard output
PASSED
25be10503efc14f0c8c1f4c4f4b3df43
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; public class Sol{ static int c[]; public static void main(String[] args){ Scanner s=new Scanner(System.in); int vertices=s.nextInt(); Graph g=new Graph(vertices+1); int root=0; c=new int[vertices+1]; for(int i=0;i<vertices;i++) { int x=s.nextInt(); int y=s.nextInt(); c[i+1]=y; if(x==-1) root=i+1; else g.addEdge(x,i+1); } g.DFS(root); g.dispAns(); } } class Graph{ int vertices; LinkedList[]adj; int dp[]; Graph(int v) { vertices=v; adj=new LinkedList[v]; dp=new int[v+1]; for(int i=0;i<v;i++) { adj[i]=new LinkedList<Integer>(); } } void addEdge(int src,int des) { adj[src].add(des); } void DFS(int src) { Iterator it=adj[src].iterator(); while(it.hasNext()) { int ele=(int)it.next(); if(Sol.c[ele]==1) dp[src]++; DFS(ele); } } void dispAns() { boolean flag=false; ArrayList<Integer>al=new ArrayList<>(); for(int i=1;i<vertices;i++) { if(dp[i]==adj[i].size() && Sol.c[i]==1) { flag=true; al.add(i); } } if(!flag) { System.out.println("-1"); return ; } Collections.sort(al); for(Integer a:al) System.out.print(a+" "); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
ac117e0c80db5df7d9d12aa4bfe3cf59
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class test{ static ArrayList<Integer>[] tree; static boolean[] visited; static boolean[] disrespect; static boolean[] delete; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); StringTokenizer st; tree=new ArrayList[n+1]; disrespect=new boolean[n+1]; int root=0; for(int i=1;i<=n;i++) { st=new StringTokenizer(br.readLine()); int p=Integer.parseInt(st.nextToken()); int c=Integer.parseInt(st.nextToken()); if(tree[i]==null) { tree[i]=new ArrayList(); } if(p!=-1 && tree[p]==null) { tree[p]=new ArrayList(); } if(p==-1) { root=i; } else { tree[p].add(i); } disrespect[i]=c==0?false:true; } visited=new boolean[n+1]; delete=new boolean[n+1]; dfs(root); int count=0; for(int i=1;i<=n;i++) { if(delete[i]) { System.out.print(i+" "); count++; } } if(count==0) { System.out.println(-1); } } public static void dfs(int node) { if(visited[node]) { return; } visited[node]=true; boolean possible = disrespect[node]; int size =tree[node].size(); for(int i=0;i<size;i++) { possible=possible && disrespect[tree[node].get(i)]; dfs(tree[node].get(i)); } delete[node]=possible; } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
9649d09f8aaeae6a10500857d43d742a
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; public class torem { static int po[]; static ArrayList<Integer> ar[]; static ArrayList<Integer> anss=new ArrayList<Integer>();; 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 void dfs(int cur) { if(po[cur]==1) { boolean ans=(po[cur]==1); for(int x:ar[cur]) { if(po[x]==0) { ans=false; break; } } if(ans) { anss.add(cur); } } for(int x:ar[cur]) { dfs(x); } } public static void main(String args[]) { FastReader scan=new FastReader(); // Scanner scan=new Scanner(System.in); int n=scan.nextInt(); ar=new ArrayList[n]; for(int i=0;i<n;i++) { ar[i]=new ArrayList<Integer>(); } po=new int[n]; int root=0; for(int i=0;i<n;i++) { int p=scan.nextInt()-1; int c=scan.nextInt(); if(p==-2) { root=i; continue; } ar[p].add(i); po[i]=c; } //System.out.println(); po[root]=0; //System.out.println(ar[0].get(0)+" "+ar[0].get(1)+" "+ar[0].get(2) +" " +po[2]+" "+po[3]+" "+po[4]); //System.out.println(root); dfs(root); //System.out.println(anss.size()); Collections.sort(anss); if(anss.size()>=1) { for(int x:anss)System.out.println(x+1); }else { System.out.println(-1); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
9f578f99bc711af165bc38556df31481
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static final long mod = (long)Math.pow(10, 9) + 7; public static void main (String[] args) throws IOException{ FastReader f=new FastReader(); int n = f.nextInt(); ArrayList<Integer>[] e = new ArrayList[n]; for (int i=0;i<n;i++) e[i] = new ArrayList<Integer>(); int[] r = new int[n]; int[] ps = new int[n]; int root=0; for (int i=0;i<n;i++) { int p = f.nextInt()-1; r[i] = f.nextInt(); if (p!=-2) e[p].add(i); else root = i; ps[i] = p; } ArrayList<Integer> ans = new ArrayList<Integer>(); for (int curr=0;curr<n;curr++) { boolean cr = false; for (int c:e[curr]) { if (r[c]==0) { cr = true; break; } } if (!cr && r[curr]!=0) { ans.add(curr+1); for (int c:e[curr]) { ps[c] = ps[curr]; } } } if (ans.size()==0) System.out.println(-1); else { for (int i=0;i<ans.size();i++) System.out.print(ans.get(i)+" "); } } // public static void dfs(int[] r,ArrayList<Integer>[] e,int curr,int[] ps,ArrayList<Integer> ans) { // boolean cr = false; // for (int c:e[curr]) { // if (r[c]==0) { // cr = true; // break; // } // } // if (!cr && r[curr]!=0) { // ans.add(curr+1); // for (int c:e[curr]) { // ps[c] = ps[curr]; // } // } // for (int c:e[curr]) dfs(r,e,c,ps,ans); // } public static int binlog( int bits ){ int log = 0; if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; } if( bits >= 256 ) { bits >>>= 8; log += 8; } if( bits >= 16 ) { bits >>>= 4; log += 4; } if( bits >= 4 ) { bits >>>= 2; log += 2; } return log + ( bits >>> 1 ); } 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
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
cdf483bbb6bac69397762ae0eed0a5a8
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import javafx.util.Pair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class C { static StringTokenizer st; static BufferedReader br; public static String nextToken() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } static String nextString() throws IOException { return br.readLine(); } static char nextChar() throws IOException { return (char) br.read(); } static int nextInt() { return Integer.parseInt(nextToken()); } static double nextDouble() { return Double.parseDouble(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static ArrayList<Pairs>[] t; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = nextInt(); t = new ArrayList[n]; int start = 0; for (int i = 0; i < n; i++) { t[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { int x = nextInt(); if (x != -1) { t[x - 1].add(new Pairs(i, nextInt())); } else { start = i; if (nextInt() == 1) { pw.print(-1); pw.close(); System.exit(0); } } } bfs(start); if (ans.size() == 0) { pw.print(-1); } else { int[] anss = new int[ans.size()]; for (int i = 0; i < ans.size(); i++) { anss[i] = ans.get(i); } Arrays.sort(anss); for (int i = 0; ans.size() > i; i++) { pw.print(anss[i] + 1 + " "); } } pw.close(); } static ArrayList<Integer> ans = new ArrayList<>(); private static void bfs(int start) { ArrayList<ArrayList<Pairs>> queue = new ArrayList<>(1000); queue.add(new ArrayList<>(1000)); for (int i = 0; i < t[start].size(); i++) { queue.get(0).add(t[start].get(i)); } int index = 0; while (queue.size() != index) { for (int i = 0; i < queue.get(index).size(); i++) { boolean bl = true; int k = queue.get(index).get(i).x; if (queue.get(index).get(i).y == 0) { bl = false; } queue.add(new ArrayList<>()); for (int j = 0; j < t[k].size(); j++) { if (t[k].get(j).y == 0) { bl = false; } queue.get(index).add(t[k].get(j)); } if (bl == true) { ans.add(k); } } index++; } } static class Pairs { public int x; public int y; public Pairs(int x, int y) { this.x = x; this.y = y; } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
528fb666e9860008bea58cfa3194cb92
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; import java.io.*; public class CodeForces { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); // int t=s.nextInt(); // while(t-->0){ int n=s.nextInt(); int[] p=new int[n]; int[] c=new int[n]; boolean v[]=new boolean[n]; for(int i=0;i<n;i++){ int a=s.nextInt(); int b=s.nextInt(); if(a!=-1){ if(b==0){ v[a-1]=true; v[i]=true; } } else{ if(b==0) v[i]=true; } } int flag=0; for(int i=0;i<n;i++){ if(!v[i]){flag=1; System.out.print((i+1)+" ");} } if(flag==1) System.out.println(); else System.out.println(-1); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
d95dca40abf52f7e902759ef56abc124
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static class Node { int n; ArrayList<Node> list = new ArrayList(); int val; Node(int name) { n = name; } } public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int non = in.nextInt(); HashMap<Integer, Node> map = new HashMap(); for (int x = 0; x < non; x++) { Node add = new Node(x + 1); map.put(x + 1, add); } Node head = null; for (int x = 1; x <= non; x++) { int par = in.nextInt(); int val = in.nextInt(); if (par == -1) { head = map.get(x); } else { map.get(par).list.add(map.get(x)); map.get(x).val = val; } } ArrayList<Integer> list = new ArrayList(); dfs(head, list); if (list.size() == 0) System.out.println(-1); Collections.sort(list); for (int ele : list) System.out.print(ele + " "); } private static void dfs(Node head, ArrayList<Integer> list) { if (head == null) return; if (head.val == 1) { boolean flag = true; for (Node node : head.list) { if (node.val == 0) { flag = false; break; } } if (flag) list.add(head.n); } for (Node node : head.list) { dfs(node, list); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
0f0b988164ccf8e07ab0c5d057c7ae09
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class C { public void solve() throws IOException { int n = nextInt(); ArrayList<Integer>[] g = new ArrayList[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } int[] c = new int[n]; int root = 0; for (int i = 0; i < n; i++) { int v = nextInt() - 1; c[i] = nextInt(); if (v == -2) { root = i; } else { g[v].add(i); } } ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < n; i++) { if (c[i] == 0) continue; boolean de = true; for (int x : g[i]) { if (c[x] == 0) { de = false; } } if (de) ans.add(i); } if (ans.size() == 0) { System.out.println(-1); } Collections.sort(ans); for (int x : ans) { System.out.print((x + 1) + " "); }/* boolean[] used = new boolean[n]; Stack<Integer> dfs = new Stack<>(); dfs.push(root); used[root] = true; while (!dfs.isEmpty()) { int cur = dfs.pop(); for (int i = 0; i < g[cur].size(); i++) { int next = g[cur].get(i); if (!used[next]) { used[next] = true; dfs.push(next); if (c[next] == 0) { c[cur] = 0; } } } } Set<Integer> del = new HashSet<>(); for (int i = 0; i < n; i++) { if (c[i] == 1) { del.add(i); } } if (del.isEmpty()) { System.out.println(-1); return; } for (int x : del) { System.out.print((x + 1) + " "); }*/ } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public int[] nextArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new C().run(); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
ce1b1e2641799ad67b2e6b73b1047b4c
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
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.util.Set; import java.util.InputMismatchException; import java.util.HashMap; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author dmytro.prytula [email protected] */ 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); BQueen solver = new BQueen(); solver.solve(1, in, out); out.close(); } static class BQueen { int n; boolean[] used; Map<Integer, Set<Integer>> graph = new HashMap<>(); int[] respect; Set<Integer> toDelete = new HashSet<>(); public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); used = new boolean[n + 1]; respect = new int[n + 1]; int root = -1; for (int i = 0; i < n; i++) { int to = in.nextInt(); if (to != -1) { graph.computeIfAbsent(i + 1, (key) -> new HashSet<>()); graph.computeIfAbsent(to, (key) -> new HashSet<>()); graph.get(i + 1).add(to); graph.get(to).add(i + 1); } else { root = i + 1; } respect[i + 1] = in.nextInt(); } dfs(root); ArrayList<Integer> anss = new ArrayList<>(toDelete); anss.sort(Comparator.naturalOrder()); if (anss.size() != 0) { for (int val : anss) { out.print(val).printSpace(); } out.printLine(); } else out.printNoAns(); } private void dfs(int from) { used[from] = true; boolean match = respect[from] == 1; for (int to : graph.getOrDefault(from, new HashSet<>())) { if (!used[to]) { match &= respect[to] == 1; dfs(to); } } if (match) toDelete.add(from); } } 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 OutputWriter printLine() { writer.println(); return this; } public OutputWriter printSpace() { writer.print(' '); return this; } public void close() { writer.close(); } public OutputWriter print(int i) { writer.print(i); return this; } public OutputWriter printLine(int i) { writer.println(i); return this; } public void printNoAns() { this.printLine(-1); } } 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; } 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
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
bab502ecc298e2028e6dcc7d650ebe2f
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.HashSet; import java.util.Set; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Arrays; import java.util.HashMap; public class cdefrc{ static ArrayList<Integer>[]adj; public static void main(String[] args) throws IOException { MScanner sc=new MScanner(System.in); //BufferedReader br=new BufferedReader((new InputStreamReader(System.in))); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int[]print=new int[n];int count=0; int[]c=new int[n]; int[]p=new int[n]; adj=new ArrayList[n]; for(int i=0;i<n;i++) { adj[i]=new ArrayList<Integer>(); } for(int i=0;i<n;i++) { p[i]=sc.nextInt()-1; c[i]=sc.nextInt(); if(p[i]!=-2) adj[p[i]].add(i); } for(int i=0;i<n;i++) { if(c[i]==1) { boolean r=false; for(int j:adj[i]) { if(c[j]==0) { r=true;break; } } if(!r) { print[count++]=i+1; //adj[p[i]].remove(i); } } } if(count==0)pw.println(-1); else { for(int i=0;i<count;i++) { pw.print(print[i]+" "); } } pw.close(); pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
1bd6635486e143dfb708918501483354
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; public class C1143 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int ans[] = new int[t+1]; int p[] = new int[t+1]; int c[] = new int[t+1]; int end = 0,z = 0; int i,j; for(i=1;i<=t;i++) { p[i] = sc.nextInt(); c[i] = sc.nextInt(); ans[i] = -1; } for(i=1;i<=t;i++) { if(c[i]==0 && p[i]!=-1) { ans[p[i]] = 0; ans[i] = 0; } else if(c[i]==1) { if(ans[p[i]]!=0) { ans[p[i]] = 1; } if(ans[i]!=0) ans[i] = 1; } else ans[i] = 0; } int flag = 0; for(i=1;i<=t;i++) { if(ans[i]==1) { System.out.println(i); flag = 1; } } if(flag==0) System.out.println(-1); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
91ca5096ecc102fdee4a00879d97d2f0
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.ObjectOutputStream.PutField; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.StringTokenizer; import java.util.stream.Collectors; import org.omg.CORBA.PUBLIC_MEMBER; public class TaskC { public static void main(String[] args) { final FastScanner in = new FastScanner(System.in); final PrintWriter out = new PrintWriter(System.out); final int n = in.nextInt();// number of nodes final int[][] a = new int[n][2];// (i-1) -> child -> parent final Map<Integer, List<Integer>> tree = new HashMap<Integer, List<Integer>>(); // parent // ->chield for (int i = 0; i < n; i++) { final int p = in.nextInt() - 1; final int c = in.nextInt(); a[i][0] = p; a[i][1] = c; List<Integer> nodes = tree.get(p); if (nodes == null) { nodes = new ArrayList<Integer>(); tree.put(p, nodes); } nodes.add(i); } List<Integer> result = solution(n, new Tree(a, tree)); if (result.isEmpty()) { out.println("-1"); } if (!result.isEmpty()) { for (Integer node : result) { int c = node + 1; out.print(c + " "); } out.println(""); } out.close(); in.close(); } private static List<Integer> solution(final int n, Tree tr) { List<Integer> removed = new LinkedList<Integer>(); Set<Integer> removedNodes = new HashSet<>(); for (int i = 0; i < n; i++) { if (removedNodes.contains(i)) { continue; } if (tr.remove(i)) { removed.add(i); removedNodes.add(i); } } return removed; } static class Tree { final int[][] parentArray; final Map<Integer, List<Integer>> chieldMap; public Tree(final int[][] a, final Map<Integer, List<Integer>> tree) { this.parentArray = a; this.chieldMap = tree; } // node to remove public boolean remove(int p) { if (parentArray[p][1] == 0) { return false; } final int newParent = parentArray[p][0]; List<Integer> chields = chieldMap.getOrDefault(p, Collections.emptyList()); // check for respect for (Integer chield : chields) { if (parentArray[chield][1] == 0) return false; } // removing for (Integer chield : chields) { parentArray[chield][0] = newParent; } chieldMap.remove(p); return true; } } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { return next(); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
918b1ac69c369c47a686e38f52c55f89
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; public final class Main{ public static boolean[] prime; public static final class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public long nextLong() { return Long.parseLong(next()); } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { String line = ""; if (st.hasMoreTokens()) line = st.nextToken(); else try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } while (st.hasMoreTokens()) line += " " + st.nextToken(); return line; } public double nextDouble() { return Double.parseDouble(next()); } } public static final class MathFunction{ public static long gcd(long a, long b) { long var; while (a % b > 0) { var = b; b = a % b; a = var; } return b; } public static int nod(long x) { int i=0; while(x!=0) { i++; x=x/10; } return i; } public static int[] FastradixSort(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 void Primesieve(int n) { for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p < n; p++) { if (prime[p] == true) { for (int i = p * p; i < n; i += p) prime[i] = false; } } } } public static class Node implements Comparable<Node>{ int x; int p; int c; public Node(int a) { x=a; c=1; } public int compareTo(Node b) { return this.x-b.x; } } public static void main(String args[]) { FastScanner sc=new FastScanner(); PrintWriter pw=new PrintWriter(System.out); int n,i,a,b,c,x,y; n=sc.nextInt(); Node[] arr=new Node[n+1]; int[] prr=new int[n+1]; PriorityQueue<Node> list=new PriorityQueue<Node>(); for(i=1;i<=n;i++) { arr[i]=new Node(i); } for(i=1;i<=n;i++) { x=sc.nextInt(); y=sc.nextInt(); arr[i].p=y; prr[i]=x; if((x!=-1)&&(y==0)) { arr[x].c=0; } } for(i=1;i<n+1;i++) { if(prr[i]==-1) continue; if((arr[i].p==1)&&(arr[i].c==1)) { list.add(arr[i]); } } if(list.size()==0) { System.out.println(-1); return; } for(Node p:list) { pw.print(p.x+" "); if(arr[prr[p.x]].p==1) { if((p.c==0)&&(arr[prr[p.x]].c==1)) { arr[prr[p.x]].c=0; list.remove(arr[prr[p.x]]); } } } pw.flush(); pw.close(); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
0398fc83fb61195e550c6f0cb2a95779
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; public final class Main{ public static boolean[] prime; public static final class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public long nextLong() { return Long.parseLong(next()); } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { String line = ""; if (st.hasMoreTokens()) line = st.nextToken(); else try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } while (st.hasMoreTokens()) line += " " + st.nextToken(); return line; } public double nextDouble() { return Double.parseDouble(next()); } } public static final class MathFunction{ public static long gcd(long a, long b) { long var; while (a % b > 0) { var = b; b = a % b; a = var; } return b; } public static int nod(long x) { int i=0; while(x!=0) { i++; x=x/10; } return i; } public static int[] FastradixSort(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 void Primesieve(int n) { for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p < n; p++) { if (prime[p] == true) { for (int i = p * p; i < n; i += p) prime[i] = false; } } } } public static class Node implements Comparable<Node>{ int x; int p; int c; public Node(int a) { x=a; c=1; } public int compareTo(Node b) { return this.x-b.x; } } public static void main(String args[]) { FastScanner sc=new FastScanner(); PrintWriter pw=new PrintWriter(System.out); int n,i,a,b,c,x,y; n=sc.nextInt(); Node[] arr=new Node[n+1]; int[] prr=new int[n+1]; PriorityQueue<Node> list=new PriorityQueue<Node>(); for(i=1;i<=n;i++) { arr[i]=new Node(i); } for(i=1;i<=n;i++) { x=sc.nextInt(); y=sc.nextInt(); arr[i].p=y; prr[i]=x; if((x!=-1)&&(y==0)) { arr[x].c=0; } } for(i=1;i<n+1;i++) { if(prr[i]==-1) continue; if((arr[i].p==1)&&(arr[i].c==1)) { list.add(arr[i]); } } if(list.size()==0) { System.out.println(-1); return; } for(Node p:list) { pw.print(p.x+" "); if(arr[prr[p.x]].p==1) { if((p.c==0)&&(arr[prr[p.x]].c==1)) { arr[prr[p.x]].c=0; list.remove(arr[prr[p.x]]); } } } pw.flush(); pw.close(); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
f91a4b0ba4990cf961f871efd87a22d4
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); int[] par = new int[n], arr = new int[n]; for(int i = 0; i < n; i++) { par[i] = scn.nextInt() - 1; arr[i] = scn.nextInt(); } int[][] g = parentToG(par); boolean print = false; for(int u = 0; u < n; u++) { boolean lol = arr[u] == 1; for(int v : g[u]) { lol &= arr[v] == 1; } if(lol) { print = true; out.print(u + 1 + " "); } } if(!print) { out.print(-1); } out.println(); } int[][] parentToG(int[] par) { int n = par.length; int[] ct = new int[n]; for (int i = 0; i < n; i++) { if (par[i] >= 0) { ct[par[i]]++; } } int[][] g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[ct[i]]; } for (int i = 0; i < n; i++) { if (par[i] >= 0) { g[par[i]][--ct[par[i]]] = i; } } return g; } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new Main(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
3f94228c139a1b51f7ca91a0065c7d2f
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); int[] par = new int[n], arr = new int[n]; for(int i = 0; i < n; i++) { par[i] = scn.nextInt() - 1; arr[i] = scn.nextInt(); } int[][] g = parentToG(par); boolean print = false; StringBuilder sb = new StringBuilder(); for(int u = 0; u < n; u++) { boolean lol = arr[u] == 1; for(int v : g[u]) { lol &= arr[v] == 1; } if(lol) { print = true; sb.append(u + 1 + " "); } } if(!print) { sb.append(-1); } out.println(sb); } int[][] parentToG(int[] par) { int n = par.length; int[] ct = new int[n]; for (int i = 0; i < n; i++) { if (par[i] >= 0) { ct[par[i]]++; } } int[][] g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[ct[i]]; } for (int i = 0; i < n; i++) { if (par[i] >= 0) { g[par[i]][--ct[par[i]]] = i; } } return g; } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new Main(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
480f671d5080fb1790390b14843cff6e
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, sc, out); out.close(); } static class Task { public void dfs(int u,PriorityQueue<Integer> que,boolean[] jud,int[] p,int[] c,ArrayList<Integer>[] tree) { boolean flag=true; for(int v:tree[u]) { if(c[v]==0) flag=false; dfs(v,que,jud,p,c,tree); } if(flag&&c[u]==1&&p[u]!=-1) { jud[u]=true; que.offer(u); } return ; } public void solve(int testNumber, InputReader sc, PrintWriter out) { int root=0; int n=sc.nextInt(); int[] c=new int[n+1]; PriorityQueue<Integer> que=new PriorityQueue<Integer>(); boolean[] jud=new boolean[n+1]; ArrayList<Integer>[] tree=new ArrayList[n+1]; int[] p=new int[n+1]; ArrayList<Integer> ans=new ArrayList<Integer>(); for(int i=1;i<=n;i++) tree[i]=new ArrayList<Integer>(); for(int i=1;i<=n;i++) { p[i]=sc.nextInt(); c[i]=sc.nextInt(); if(p[i]==-1) root=i; else tree[p[i]].add(i); } dfs(root,que,jud,p,c,tree); if(que.size()==0) out.println("-1"); else { while(!que.isEmpty()) { int u=que.poll(); ans.add(u); /* boolean flag=true; for(int v:tree[p[u]]) { if(c[v]==0) { flag=false; break; } } for(int v:tree[u]) { p[v]=p[u]; tree[p[u]].add(v); if(c[v]==0) flag=false; } if(p[p[u]]!=-1&&c[p[u]]==1&&flag&&!jud[p[u]]&&c[p[u]]==1) { que.add(p[u]); jud[p[u]]=true; }*/ } for(int k:ans) out.print(k+" "); out.println(); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
91b4e780deda30a083f7622eb6d91781
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class C { public static void main(String[] args) throws IOException{ FastReader reader = new FastReader(); int n = reader.nextInt(); int[] p = new int[n + 1]; int[] c = new int[n + 1]; List<List<Integer>> list = new ArrayList<>(); List<List<Integer>> dop = new ArrayList<>(); for(int i = 0; i <= n; i++) { list.add(new ArrayList<>()); dop.add(new ArrayList<>()); } for(int i = 1; i <= n; i++) { p[i] = reader.nextInt(); c[i] = reader.nextInt(); if(p[i] != -1) list.get(p[i]).add(i); } boolean flag = false; int count = 0; Set<Integer> deleted = new HashSet<>(); while(!flag) { flag = true; for(int i = 1; i <= n; i++) { if(deleted.contains(i)) continue; if(!check(list, dop, p, c, i)) { System.out.print(i + " "); deleted.add(i); for(int x : list.get(i)) { p[x] = p[i]; } list.get(p[i]).add(i); flag = false; count++; } } } if(count == 0) System.out.println(-1); } public static boolean check(List<List<Integer>> list, List<List<Integer>> dop, int[] p, int[] c, int v) { if(c[v] == 1) { for(int x : list.get(v)) { if(c[x] == 0) return true; } for(int l : dop.get(v)) { for(int x : list.get(l)) { if(c[x] == 0) return true; } } return false; } return true; } private static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
0ca4d579432d512414f9def07c8d7e8f
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class z71 { static ArrayList<Integer> adj[]; static TreeSet<Integer> ans = new TreeSet<>(); public static void solve(InputReader in, PrintWriter out) throws Exception { int n = in.nextInt(); adj = new ArrayList[n+1]; for(int i=0;i<=n;i++) adj[i]=new ArrayList<>(); int[] cis = new int[n+1]; int[] pis = new int[n+1]; int root=-1; for(int i=1;i<=n;i++) { int pi = in.nextInt(); cis[i] = in.nextInt(); pis[i] = pi; if(pi!=-1) { adj[pi].add(i); adj[i].add(pi); } else root= i; } DFS(root,cis,pis); // out.println(ans); if(ans.isEmpty()) out.println(-1); else for(int val : ans) out.print(val+" "); out.println(); } public static void DFS(int n, int[] cis, int[] pis) { if(cis[n]==1) { int and = 1; for(int ch : adj[n]) { if(pis[n]!=ch) and = and & cis[ch]; } //System.out.println(and); if(and==1) ans.add(n); } for(int val : adj[n]) { if(pis[n]!=val) DFS(val,cis,pis); } } ///////////////////////////////////////////////////////// private final static long hash(long x, long y) { x += offset; y += offset; return x << 32 | y; } private final static int offset = (int) 3e5; public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public String nextLine() throws IOException { return reader.readLine(); } 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
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
d0a54c88f6f82d9a18de1bc0ab75d324
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class MainClass { public static void main(String args[])throws IOException { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); int p[]=new int[n]; int c[]=new int[n]; int d[]=new int[n]; for(int i=0;i<n;i++) { String t_input[]; t_input=br.readLine().split(" "); p[i]=Integer.parseInt(t_input[0]); c[i]=Integer.parseInt(t_input[1]); d[i]=1; if(p[i]==-1) d[i]=0; } for(int i=0;i<n;i++) { if(c[i]==0 && p[i]!=-1) { d[i]=0; d[p[i]-1]=0; } } int count=0; for(int i=0;i<n;i++) { if(d[i]==1) { ++count; System.out.print((i+1)+" "); } } if(count==0) System.out.println("-1"); } catch(NumberFormatException x){} } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
214fc6638111163857dfe4eb7eea4610
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class MainClass { public static void main(String args[])throws IOException { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); int p[]=new int[n]; int c[]=new int[n]; int d[]=new int[n]; Set<Integer> set= new TreeSet<Integer>(); for(int i=0;i<n;i++) { String t_input[]; t_input=br.readLine().split(" "); p[i]=Integer.parseInt(t_input[0]); c[i]=Integer.parseInt(t_input[1]); d[i]=1; if(p[i]==-1) d[i]=0; // System.out.println(d[i]); } for(int i=0;i<n;i++) { if(c[i]==0 && p[i]!=-1) { // System.out.println((i)+" "+p[i]); d[i]=0; d[p[i]-1]=0; } } for(int i=0;i<n;i++) { //System.out.println(d[i]); // System.out.println((i+1)+" "); // if(p[i]!=-1 && d[p[i]-1]==1) //{ // p[i]=p[p[i]-1]; if(d[i]==1) set.add((i+1)); // } } int c1=0; Iterator iterator = set.iterator(); while(iterator.hasNext()) { ++c1; int element = (int) iterator.next(); System.out.print(element+" "); } if(c1==0) System.out.println("-1"); } catch(NumberFormatException x){} } } /* __________TEST INPUT: int test=Integer.parseInt(br.readLine()); __________n INPUT: int n=Integer.parseInt(br.readLine()); __________ARRAY INPUT: String a_input[]; a_input=br.readLine().split(" "); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(a_input[i]); } __________INPUT FOR TWO SPACE SEPARATED INTEGERS: String t_input[]; t_input=br.readLine().split(" "); int n=Integer.parseInt(t_input[0]); int k=Integer.parseInt(t_input[1]); */
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
8bbfb0516d83c3aebe37a1bff157345c
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class TaskA { private boolean eof; private BufferedReader br; private StringTokenizer st; private BufferedWriter out; public static void main(String[] args) throws IOException { new TaskA().run(); } private String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(nextToken()); } private long nextLong() { return Long.parseLong(nextToken()); } private double nextDouble() { return Double.parseDouble(nextToken()); } private String nextLine() throws IOException { return br.readLine(); } private void run() throws IOException { InputStream input = System.in; PrintStream output = System.out; try { File f = new File("a.in"); if (f.exists() && f.canRead()) { input = new FileInputStream(f); output = new PrintStream("a.out"); } } catch (Throwable ignored) { } br = new BufferedReader(new InputStreamReader(input)); out = new BufferedWriter(new PrintWriter(output)); solve(); br.close(); out.close(); } int parent[]; ArrayList<Set<Integer>> childs; ArrayList<Integer> ans = new ArrayList<>(); boolean[] respects; TreeSet<Integer> toDelete = new TreeSet<>(); void dfs(int x) { for (int child : childs.get(x)) { dfs(child); } check(x); } void check(int x) { boolean delete = true; for (int child : childs.get(x)) { if (respects[child]) delete = false; } if (delete && !respects[x]) toDelete.add(x); } private void solve() throws IOException { int n = nextInt(); childs = new ArrayList<>(); for (int i = 0; i <= n; i++) { childs.add(new HashSet<>()); } respects = new boolean[n + 1]; parent = new int[n + 1]; int cur = 1; for (int i = 1; i <= n; i++) { int p = nextInt(); parent[i] = p; int c = nextInt(); respects[i] = c == 0; if (p == -1) { cur = i; continue; } childs.get(p).add(i); } dfs(cur); while (!toDelete.isEmpty()) { int del = toDelete.pollFirst(); //lowest ans.add(del); // for (int child : childs.get(del)) { // parent[child] = parent[del]; // } // childs.get(parent[del]).remove(del); // for (int child : childs.get(del)) { // childs.get(parent[del]).add(child); // } // // check(parent[del]); } StringBuilder builder = new StringBuilder(); for (int c : ans) { builder.append(c); builder.append(" "); } if (ans.isEmpty()) { builder.append(-1); } out.write(builder.toString()); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
0843949081c7e30a711aedcd05192526
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class TaskA { private boolean eof; private BufferedReader br; private StringTokenizer st; private BufferedWriter out; public static void main(String[] args) throws IOException { new TaskA().run(); } private String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(nextToken()); } private long nextLong() { return Long.parseLong(nextToken()); } private double nextDouble() { return Double.parseDouble(nextToken()); } private String nextLine() throws IOException { return br.readLine(); } private void run() throws IOException { InputStream input = System.in; PrintStream output = System.out; try { File f = new File("a.in"); if (f.exists() && f.canRead()) { input = new FileInputStream(f); output = new PrintStream("a.out"); } } catch (Throwable ignored) { } br = new BufferedReader(new InputStreamReader(input)); out = new BufferedWriter(new PrintWriter(output)); solve(); br.close(); out.close(); } int parent[]; ArrayList<Set<Integer>> childs; ArrayList<Integer> ans = new ArrayList<>(); boolean[] respects; TreeSet<Integer> toDelete = new TreeSet<>(); void dfs(int x) { for (int child : childs.get(x)) { dfs(child); } check(x); } void check(int x) { boolean delete = true; for (int child : childs.get(x)) { if (respects[child]) delete = false; } if (delete && !respects[x]) toDelete.add(x); } private void solve() throws IOException { int n = nextInt(); childs = new ArrayList<>(); for (int i = 0; i <= n; i++) { childs.add(new HashSet<>()); } respects = new boolean[n + 1]; parent = new int[n + 1]; int cur = 1; for (int i = 1; i <= n; i++) { int p = nextInt(); parent[i] = p; int c = nextInt(); respects[i] = c == 0; if (p == -1) { cur = i; continue; } childs.get(p).add(i); } dfs(cur); while (!toDelete.isEmpty()) { int del = toDelete.pollFirst(); //lowest ans.add(del); for (int child : childs.get(del)) { parent[child] = parent[del]; } // childs.get(parent[del]).remove(del); // for (int child : childs.get(del)) { // childs.get(parent[del]).add(child); // } // // check(parent[del]); } StringBuilder builder = new StringBuilder(); for (int c : ans) { builder.append(c); builder.append(" "); } if (ans.isEmpty()) { builder.append(-1); } out.write(builder.toString()); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
6bf590f9ac34e1f7df3d0e84690165ea
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.io.*; import java.math.*; import java.text.*; public class Queen { static ArrayList<ArrayList<Integer>> ar = new ArrayList<ArrayList<Integer>>(); static Set<Integer> ans = new HashSet<>(); static void dfs(int root, int c[],boolean vis[],int parent,boolean isOne) { vis[root-1]=true; int p=0; if( !isOne) ans.add(root); if(!isOne ) ans.add(parent); for(int j:ar.get(root)) { if(!vis[j-1]) { if(c[j-1]==0) dfs(j,c,vis,root,false); else dfs(j,c,vis,root,true); } } } static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = 1; while (t > 0) { int n=i(); int c[]=new int[n]; for(int i=0;i<=n+1;i++) { ar.add(new ArrayList<Integer>()); } int root=0; for(int i=0;i<n;i++) { int a=i(); if(a!=-1) { ar.get(a).add(i+1); } else { root=i+1; } c[i]=i(); } int ch=0; boolean vis[]=new boolean[n]; dfs(root,c,vis,-1,false); // System.out.println(ans); for(int i=1;i<=n;i++) { if(!ans.contains(i)) { ch=1; System.out.print(i+" "); } } if(ch==0) System.out.print("-1"); System.out.println(""); // System.out.println(ar+" "+root); t--; } // long l=l(); // String s=s(); // ONLY BEFORE SPACE IN STRING , ELSE USE BUFFER-READER } public static long pow(long a, long b) { long m = 1000000007; long result = 1; while (b > 0) { if (b % 2 != 0) { result = (result * a) % m; b--; } a = (a * a) % m; b /= 2; } return result % m; } 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 pair { int x, y; pair(int x, int y) { this.x = x; this.y = y; } } class CompareValue { static void compare(pair arr[], int n) { Arrays.sort(arr, new Comparator<pair>() { public int compare(pair p1, pair p2) { return p1.y - p2.y; } }); } } class CompareKey { static void compare(pair arr[], int n) { Arrays.sort(arr, new Comparator<pair>() { public int compare(pair p1, pair p2) { return p2.x - p1.x; } }); } } 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); } public double readDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, Int()); } 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, Int()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } 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]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } 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; } } /** * TO SORT VIA TWO KEYS , HERE IT IS ACCORDING TO ASCENDING ORDER OF FIRST AND * DESC ORDER OF SECOND * LIST name-list * ARRAYLIST * COPY PASTE * * Collections.sort(list, (first,second) ->{ if(first.con >second.con) return -1; else if(first.con<second.con) return 1; else { if(first.index >second.index) return 1; else return -1; } }); * */ /** * DECIMAL FORMATTER Double k = in.readDouble(); System.out.println(k); DecimalFormat df = new DecimalFormat("#.##"); System.out.print(df.format(k)); out.printLine(k); * * */
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
ab19df2c306c328e812092770e33609e
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.Scanner; import java.util.TreeSet; public class Queen { public static class Node implements Comparable<Node> { int c = 0; int ind = 0; Node p = null; TreeSet<Node> child = new TreeSet<Node>(); public void delete() { for (Node e : this.child) { e.p = this.p; } p = null; } public boolean disrespect() { for (Node e : this.child) { if (e.c == 0) return false; } return c == 0 ? false : true; } @Override public int compareTo(Node o) { return this.ind - o.ind; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Node[] tree = new Node[n]; for (int i = 0; i < n; i++) { tree[i] = new Node(); } int root = 0; for (int i = 0; i < n; i++) { int p = sc.nextInt() - 1; int c = sc.nextInt(); tree[i].c = c; tree[i].ind = i + 1; if (p == -2) { root = i; } else { tree[i].p = tree[p]; tree[p].child.add(tree[i]); } } sim(tree, tree[root]); if (order.size() == 0) { System.out.println(-1); } else { for (Integer e : order) { System.out.print(e + " "); } } } static TreeSet<Integer> order = new TreeSet<Integer>(); public static void sim(Node[] tree, Node root) { if (root.disrespect()) { root.delete(); order.add(root.ind); } for (Node e : root.child) { sim(tree, e); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
f53f8f3d01696b628d3b24d296c931e3
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.Scanner; /** * * @author arabtech */ public class Nirvana { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] c = new int[n]; int[] p = new int[n]; boolean[] nodes = new boolean[n]; int ans=n; for (int i = 0; i < n; i++) { p[i] = sc.nextInt(); c[i]=sc.nextInt(); if(p[i]==-1){ nodes[i]=true; } } for (int i = 0; i < n; i++) { if (c[i] == 0) { if(p[i]!=-1){ nodes[p[i] - 1] = true; } nodes[i]=true; } } for(int i=0;i<n;i++){ if(nodes[i]){ ans--; } } if (ans == 0) { System.out.print(-1); } else{ for(int i=0;i<n;i++){ if(!nodes[i]){ System.out.print((i+1)+" "); } } } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
267149e0676af25b689e691072153ed4
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.io.*; import java.util.*; public class Main { private static Reader fr; private static OutputStream out; private static final int delta = (int) 1e9 + 7; private static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1024]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } public int[] nextArray(int n) throws IOException { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } } private static void print(Object str) { try { out.write(str.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } private static void println(Object str) { try { out.write((str.toString() + "\n").getBytes()); } catch (IOException e) { e.printStackTrace(); } } private static void printArray(int arr[]) { for (int val : arr) { print(val + " "); } println(""); } private static long add(long a, long b) { return add(a, b, delta); } private static long add(long a, long b, long mod) { return ((a % mod) + (b % mod)) % mod; } private static long multiply(long a, long b) { return ((a % delta) * (b % delta)) % delta; } public static double multiply(double a, double b) { return ((a % delta) * (b % delta)) % delta; } private static long pow(int base, int pow) { if (pow == 0) return 1; if (pow == 1) return base; long halfPow = pow(base, pow / 2); if ((pow & 1) == 0) return multiply(halfPow, halfPow); return multiply(halfPow, multiply(base, halfPow)); } private static long gcd(long a, long b) { if (a == 0 || b == 0) return a == 0 ? b : a; return gcd(b, a % b); } private static long kadane(int[] arr) { int size = arr.length; long max_so_far = Integer.MIN_VALUE, max_ending_here = 0; for (int anArr : arr) { max_ending_here = max_ending_here + anArr; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } public static void main(String args[]) throws IOException { run(); } private static void run() throws IOException { fr = new Reader(); out = new BufferedOutputStream(System.out); solve(); out.flush(); out.close(); } static int mod=1000000007; static int k=0; private static void solve() throws IOException { int t = 1;//fr.nextInt(); while (t-- > 0) { int n = fr.nextInt(); int a[]=new int[n]; int ans[]=new int[n]; int root = -1; ArrayList<Integer>[] g= new ArrayList[n]; for (int i = 0; i < n; i++) g[i] =new ArrayList<Integer>(); for(int i=0;i<n;i++) { int u=fr.nextInt()-1; a[i]=fr.nextInt(); if(u==-2) { root = i; continue; } g[u].add(i); g[i].add(u); } task0(g,a,ans,root,-1); Arrays.sort(ans,0,k); for(int i=0;i<k;i++) System.out.print(ans[i]+1+" "); if(k==0) System.out.print("-1"); } } static int task0(ArrayList<Integer>[] g ,int a[],int ans[],int s,int p) { int tmp = a[s]; for(int i=0;i<g[s].size();i++) if(g[s].get(i)!=p) tmp &= task0(g,a,ans,g[s].get(i),s); if(tmp==1) ans[k++]=s; return a[s]; } static void print1(ArrayList<Integer>[] g,int n) { for(int i=0;i<n;i++) { System.out.print(i+1+"\t"); for(int j=0;j<g[i].size();j++) System.out.print(g[i].get(j)+1+" "); System.out.println(); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
a11ee9683d57eeb5a486bfe1bd99c30c
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.List; import static java.lang.Math.*; public class D { public static void main(String[] args) throws Exception { InputReader scan = new InputReader(new BufferedInputStream(System.in)); int n = scan.nextInt(); Node[] nodes = new Node[n];for (int i=0;i<n;i++)nodes[i]=new Node(i); List<Node> unres = new ArrayList<Node>(n); Node root = null; for (int i=0;i<n;i++) { int p = scan.nextInt()-1; boolean respect1 = scan.nextInt()==0; nodes[i].respect=respect1; if (p==-2){ root=nodes[i]; } else { nodes[p].children.add(nodes[i]); nodes[i].parent = nodes[p]; } if(!respect1)unres.add(nodes[i]); } Collections.sort(unres); boolean noneDelete = true; for (Node node: unres) { if (node.parent==null)continue; boolean delete = true; for (Node n1: node.children) { if (n1.respect) { delete = false; break; } } for (List<Node> moreChildren: node.moreChildren) { for (Node n1 : moreChildren) { if (n1.respect) { delete = false; break; } } } if(delete) { System.out.print(node.key + 1); System.out.print(" "); //node.parent.children.addAll(node.children); node.moreChildren.add(node.children); noneDelete = false; } } if (noneDelete) { System.out.println(-1); } scan.close(); } static class Node implements Comparable<Node> { int key; boolean respect; Node parent = null; List<Node> children = new LinkedList<Node>(); List<List<Node>> moreChildren = new LinkedList<List<Node>>(); public Node(int i) { key=i; } public int compareTo(Node o) { return key-o.key; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void close() throws IOException { this.stream.close(); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public String next() { return nextString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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() { return Long.parseLong(nextString()); } public Double nextDouble() { return Double.parseDouble(nextString()); } public char nextCharacter() { return nextString().charAt(0); } public int[] nextIntArray(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = nextInt(); } return A; } public long[] nextLongArray(int N) { long A[] = new long[N]; for (int i = 0; i < N; i++) { A[i] = nextLong(); } return A; } public double[] nextDoubleArray(int N) { double A[] = new double[N]; for (int i = 0; i < N; i++) { A[i] = nextDouble(); } return A; } } int min(int... a) { int min = Integer.MAX_VALUE; for (int v : a) { min = Math.min(min, v); } return min; } long min(long... a) { long min = Long.MAX_VALUE; for (long v : a) { min = Math.min(min, v); } return min; } double min(double... a) { double min = Double.MAX_VALUE; for (double v : a) { min = Math.min(min, v); } return min; } int max(int... a) { int max = Integer.MIN_VALUE; for (int v : a) { max = Math.max(max, v); } return max; } long max(long... a) { long max = Long.MIN_VALUE; for (long v : a) { max = Math.max(max, v); } return max; } double max(double... a) { double max = Double.MIN_VALUE; for (double v : a) { max = Math.max(max, v); } return max; } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
4313a2f5e0bb38878081bbac5393eaf5
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class Queen549C { static class Pair { int respect,index; public Pair(int index,int respect) { this.respect= respect; this.index = index; } @Override public String toString() { // TODO Auto-generated method stub return this.index+""; } } static class FastReader { BufferedReader br; StringTokenizer st; private 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 void main(String[] args) { HashMap<Integer, ArrayList<Pair>> tree = new HashMap<>(); FastReader s= new FastReader(); int n =s.nextInt(); int root=0; for(int i=1;i<=n;i++) { tree.put(i, new ArrayList<Pair>()); } for(int i=1;i<=n;i++) { int u = s.nextInt(); int r = s.nextInt(); if(u==-1) { root= i; continue; } tree.get(u).add(new Pair(i,r)); } //System.out.println(tree); ArrayList<Integer> ans = dfs(tree,root,0,new ArrayList<Integer>(10000)); if(ans.size()==0) { System.out.println(-1); }else { Collections.sort(ans); StringBuilder str =new StringBuilder(); for(int p:ans) str.append(p+" "); System.out.println(str); } } private static ArrayList<Integer> dfs(HashMap<Integer, ArrayList<Pair>> tree, int root,int respect,ArrayList<Integer> list) { boolean c =true; if(tree.get(root).size()==0) { c=false; } ArrayList<Pair> children =tree.get(root); if(c) { for(Pair child:children) { dfs(tree,child.index,child.respect,list); } } boolean flag =true; for(Pair child:children) { if(child.respect ==0) { flag = false; break; } } if(flag && respect==1) { list.add(root); } return list; } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
719f31c718e9f19b084b0226f1e60761
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void initGraph(ArrayList<Integer> graph[]) { for(int i = 0; i<graph.length; i++) { graph[i] = new ArrayList<>(); } } public static ArrayList<Integer> graph[] = new ArrayList[(int) 1e6]; public static int c[] = new int[(int) 1e6]; public static ArrayList<Integer> ans = new ArrayList<>(); public static void dfs(int u) { boolean ok = true; if(c[u] == 0) ok = false; for(int i : graph[u]) { if(c[i] == 0) ok = false; } if(ok) ans.add(u); for(int i : graph[u]) dfs(i); } public static void solve(InputReader in, OutputWriter out) { initGraph(graph); int n = in.readInt(); int root = 0; for(int i = 0; i<n; i++) { int x = in.readInt(); if(x != -1) graph[x].add(i+1); else root = i+1; c[i+1] = in.readInt(); } dfs(root); if(ans.size() == 0) { out.println(-1); return; } Collections.sort(ans); for(int i : ans) out.print(i + " "); out.println(); } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int t = 1; while (t-- > 0) solve(in , out); out.flush(); out.close(); } } class InputReader{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
0be0bd0022476d1f8047c26d5f75971e
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; public class cf1143c { static int[] tra; public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); sc.nextLine(); HashMap<Integer, Node> map = new HashMap<>(); map.put(-2, new Node(-1,0,-3)); tra = new int[n]; ArrayList<String> input = new ArrayList<>(); for (int i =0; i < n; i++) { String in = sc.nextLine(); String[] spl = in.split(" "); int p = Integer.parseInt(spl[0])-1; int c = Integer.parseInt(spl[1]); map.put(i, new Node(i,c,p)); input.add(in); } for (int i =0; i < n; i++) { String in = input.get(i); String[] spl = in.split(" "); int parent = Integer.parseInt(spl[0])-1; int c = Integer.parseInt(spl[1]); Node p = map.get(parent); Node nee = map.get(i); tra[i] = i; if (c == 0) { p.respect++; } map.put(i, nee); } TreeSet<Node> thing = new TreeSet<>(); for (int i =0; i < n; i++) { Node get = map.get(i); if (get.respectsparents==false && get.respect == 0) { thing.add(get); } } ArrayList<Integer> order = new ArrayList<>(); // System.out.println(thing); while (thing.isEmpty()==false) { Node pop = thing.pollFirst(); order.add(pop.index+1); int par = find(pop.parent); // int par = tra[pop.parent]; // while (tra[par] != par) { // par = tra[par]; // } Node parent = map.get(par); if (pop.respectsparents) { parent.respect--; } parent.respect += pop.respect; tra[pop.index] = tra[par]; if (thing.contains(parent)) { if (parent.respect >0) { thing.remove(parent); } }else { if (parent.respect == 0 && !parent.respectsparents) { thing.add(parent); } } } if (order.size() == 0) { out.println(-1); } else { for (int ff : order) { out.print(ff); out.print(' '); } out.println(); } out.close(); } static int find(int p) { if (tra[p] == p) return p; return tra[p] = find(tra[p]); } static class Node implements Comparable<Node>{ int c; int index; int respect; boolean respectsparents; int parent; public Node(int i, int c, int par) { index = i; this.c = c; respect= 0; parent = par; respectsparents = c == 0; } @Override public int compareTo(Node o) { return index - o.index; } public String toString() { return index + " " + c + " " + respect + " " + parent + " --"; } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
7b14b1b72f6426b46e510f6344421042
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; import org.omg.CORBA.Principal; import java.awt.List; import java.io.*; import java.lang.*; public class graph { public static long mod = (long) Math.pow(10, 9) + 7; public static InputReader in = new InputReader(System.in); public static PrintWriter pw = new PrintWriter(System.out); public static ArrayList<Integer>[] adj; public static boolean[] del; public static int[] par; public static void main(String[] args) { // Code starts.. int n = in.nextInt(); //adj = new ArrayList[n+1]; del = new boolean[n+1]; par = new int[n+1]; Arrays.fill(del, true); // for(int i=0; i<=n; i++) // adj[i] = new ArrayList<Integer>(); // int[] c = new int[n+1]; for(int i=1; i<=n; i++) { int u = in.nextInt(); int ci = in.nextInt(); c[i] = ci; par[i] = u; if(ci==0) { del[i] = false; if(u!=-1) { del[u] = false; // adj[u].add(i); } } } // for(int i=1; i<=n; i++) // if(del[i]) // pw.print(i+" "); ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i=1; i<=n; i++) { if(del[i]) { ans.add(i); } } // for(int i=1; i<=n; i++) // if(!del[i]) // pw.println(i+" "+par[i]+" "); if(ans.size()>0) { for(int p: ans) pw.print(p+" "); } else pw.print(-1); // code ends... pw.flush(); pw.close(); } /* * public static void bfs(int s, int cnt) { * * Queue<Integer> que = new LinkedList<Integer>(); que.add(s); * while(!que.isEmpty()) { int p = que.poll(); vis[p] = true; comp[p] = cnt; * for(int q: adj[p]) { if(!vis[q]) que.add(q); } } * * } */ public static long bs(long[] a, long k, long m) { long l = 0; long r = a.length+1; long mid = 0; long ans = -1; while (r - l > 0) { mid = (r + l) / 2; boolean flag = fun(a, k, m, mid); if(flag) { ans = mid; r = mid; } else l = mid+1; } return ans; } public static boolean fun(long[] a, long k, long m, long mid) { //pw.println(mid); int n = a.length; long cur = 0; for(int i=0; i<m; i++) { long min = (long)Math.ceil((a[n-2]-cur)/(m-i)); long ll = 0; if(cur-1>=0) ll = lowerboundArray(a, cur-1)+1; long max = 0; if(ll+mid<=n-2) max = a[(int) (ll+mid)]-1; else max = a[n-1]; if(max<min) return false; cur = Math.min(cur+k, max); //pw.println(ll+" "+max+" "+cur+" "); } //pw.print(cur); if(cur>=a[n-2]) return true; else return false; } public static Comparator<Integer> cmp = new Comparator<Integer>() { @Override public int compare(Integer t1, Integer t2) { return t2 - t1; } }; public static int lcs(char[] X, char[] Y, int m, int n) { int L[][] = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); if (L[i][j] >= 100) return 100; } } return L[m][n]; } public static void factSieve(int[] fact, long n) { for (int i = 2; i <= n; i += 2) fact[i] = 2; for (int i = 3; i <= n; i += 2) { if (fact[i] == 0) { fact[i] = i; for (int j = i; (long) j * i <= n; j++) { fact[(int) ((long) i * j)] = i; } } } /* * int k = 1000; while(k!=1) { System.out.print(a[k]+" "); k /= a[k]; * * } */ } public static int gcd(int p2, int p22) { if (p2 == 0) return (int) p22; return gcd(p22 % p2, p2); } public static void nextGreater(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i < a.length; i++) { if (!stk.isEmpty()) { int s = stk.pop(); while (a[s] < a[i]) { ans[s] = i; if (!stk.isEmpty()) s = stk.pop(); else break; } if (a[s] >= a[i]) stk.push(s); } stk.push(i); } return; } public static void nextGreaterRev(long[] a, int[] ans) { int n = a.length; int[] pans = new int[n]; Arrays.fill(pans, -1); long[] arev = new long[n]; for (int i = 0; i < n; i++) arev[i] = a[n - 1 - i]; Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i < n; i++) { if (!stk.isEmpty()) { int s = stk.pop(); while (arev[s] < arev[i]) { pans[s] = n - i - 1; if (!stk.isEmpty()) s = stk.pop(); else break; } if (arev[s] >= arev[i]) stk.push(s); } stk.push(i); } // for(int i=0; i<n; i++) // System.out.print(pans[i]+" "); for (int i = 0; i < n; i++) ans[i] = pans[n - i - 1]; return; } public static void nextSmaller(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i < a.length; i++) { if (!stk.isEmpty()) { int s = stk.pop(); while (a[s] > a[i]) { ans[s] = i; if (!stk.isEmpty()) s = stk.pop(); else break; } if (a[s] <= a[i]) stk.push(s); } stk.push(i); } return; } public static long lcm(int[] numbers) { long lcm = 1; int divisor = 2; while (true) { int cnt = 0; boolean divisible = false; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == 0) { return 0; } else if (numbers[i] < 0) { numbers[i] = numbers[i] * (-1); } if (numbers[i] == 1) { cnt++; } if (numbers[i] % divisor == 0) { divisible = true; numbers[i] = numbers[i] / divisor; } } if (divisible) { lcm = lcm * divisor; } else { divisor++; } if (cnt == numbers.length) { return lcm; } } } public static long fact(long n) { long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static long choose(long total, long choose) { if (total < choose) return 0; if (choose == 0 || choose == total) return 1; return (choose(total - 1, choose - 1) + choose(total - 1, choose)) % mod; } public static int[] suffle(int[] a, Random gen) { int n = a.length; for (int i = 0; i < n; i++) { int ind = gen.nextInt(n - i) + i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static int[] sort(int[] a) { int n = a.length; Random gen = new Random(); for (int i = 0; i < n; i++) { int ind = gen.nextInt(n - i) + i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } Arrays.sort(a); return a; } public static long[] sort(long[] a) { int n = a.length; Random gen = new Random(); for (int i = 0; i < n; i++) { int ind = gen.nextInt(n - i) + i; long temp = a[ind]; a[ind] = a[i]; a[i] = temp; } Arrays.sort(a); return a; } public static int floorSearch(int arr[], int low, int high, int x) { if (low > high) return -1; if (x > arr[high]) return high; int mid = (low + high) / 2; if (mid > 0 && arr[mid - 1] < x && x < arr[mid]) return mid - 1; if (x < arr[mid]) return floorSearch(arr, low, mid - 1, x); return floorSearch(arr, mid + 1, high, x); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a = new ArrayList<Integer>(); for (int i = 2; i * i <= n; i++) { while (n % i == 0) { a.add(i); n /= i; } } if (n != 1) a.add(n); return a; } public static void sieve(boolean[] isPrime, int n) { for (int i = 1; i < n; i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i < n; i++) { if (isPrime[i] == true) { for (int j = (2 * i); j < n; j += i) isPrime[j] = false; } } } public static int lowerbound(ArrayList<Long> net, long c2) { int i = Collections.binarySearch(net, c2); if (i < 0) i = -(i + 2); return i; } public static int lowerboundArray(long[] a, long cur) { int i = Arrays.binarySearch(a, cur); if (i < 0) i = -(i + 2); return i; } public static int uperbound(ArrayList<Integer> list, int c2) { int i = Collections.binarySearch(list, c2); if (i < 0) i = -(i + 1); return i; } public static int uperboundArray(int[] dis, int c2) { int i = Arrays.binarySearch(dis, c2); if (i < 0) i = -(i + 1); return i; } public static int GCD(int a, int b) { if (b == 0) return a; else return GCD(b, a % b); } public static long GCD(long a, long b) { if (b == 0) return a; else return GCD(b, a % b); } public static int d1; public static int p1; public static int q1; public static void extendedEuclid(int A, int B) { if (B == 0) { d1 = A; p1 = 1; q1 = 0; } else { extendedEuclid(B, A % B); int temp = p1; p1 = q1; q1 = temp - (A / B) * q1; } } public static long LCM(long a, long b) { return (a * b) / GCD(a, b); } public static int LCM(int a, int b) { return (a * b) / GCD(a, b); } public static int binaryExponentiation(int x, int n) { int result = 1; while (n > 0) { if (n % 2 == 1) result = result * x; x = x * x; n = n / 2; } return result; } public static int[] countDer(int n) { int der[] = new int[n + 1]; der[0] = 1; der[1] = 0; der[2] = 1; for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der; } static long binomialCoeff(int n, int k) { long C[][] = new long[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previosly stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } public static long binaryExponentiation(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) result = result * x; x = (x % mod * x % mod) % mod; n = n / 2; } return result; } public static int modularExponentiation(int x, int n, int M) { int result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } public static long modularExponentiation(long x, long n, long M) { long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } public static long pow(long x, long n, long M) { long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } public static long modInverse(long q, long mod2) { return modularExponentiation(q, mod2 - 2, mod2); } public static long sie(long A, long M) { return modularExponentiation(A, M - 2, M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Long x, y; pair(long bi, long wi) { this.x = bi; this.y = wi; } public int compareTo(pair o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); return result; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return (p.x -x == 0) && (p.y - y == 0); } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } } static class tripletD implements Comparable<tripletD> { Double x, y, z; tripletD(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public int compareTo(tripletD o) { int result = x.compareTo(o.x); if (result == 0) { double x1 = o.x + o.y; result = ((Double) x1).compareTo((double) (x + y)); } return result; } public String toString() { return x + " " + y + " " + z; } public boolean equals(Object o) { if (o instanceof tripletD) { tripletD p = (tripletD) o; return (p.x - x == 0) && (p.y - y==0) && (p.z - z==0); } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } } static class tripletL implements Comparable<tripletL> { Long x, y, z; tripletL(long x, long y, long z) { this.x = x; this.y = y; this.z = z; } public int compareTo(tripletL o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); if (result == 0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if (o instanceof tripletL) { tripletL p = (tripletL) o; return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0); } return false; } public String toString() { return x + " " + y + " " + z; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode(); } } static class triplet implements Comparable<triplet> { Integer x, y, z; triplet(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(triplet o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); if (result == 0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if (o instanceof triplet) { triplet p = (triplet) o; return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0); } return false; } public String toString() { return x + " " + y + " " + z; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode(); } } /* * static class node implements Comparable<node> * * { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; } * * public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) * result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return * result; } * * @Override public int compareTo(node o) { // TODO Auto-generated method stub * return 0; } } */ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
b3a85f5a7c6024cb53430d8bbd551544
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static TreeSet<Integer> ans=new TreeSet<>(); public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine().trim()); int root=0; ArrayList<Integer> arr[]=new ArrayList[n+1]; boolean respect[]=new boolean[n+1]; for(int i=0;i<=n;i++) arr[i]=new ArrayList<>(); for(int i=1;i<=n;i++){ String inp[]=br.readLine().trim().split(" "); int a=Integer.parseInt(inp[0]); int b=Integer.parseInt(inp[1]); respect[i]=(b==0); if(a ==-1) root=i; else arr[a].add(i); } dfs(root,arr,respect); if(ans.isEmpty()) { System.out.println(-1); System.exit(0); } for(int i:ans) System.out.print(i+" "); } static void dfs(int i, ArrayList<Integer> arr[],boolean respect[]){ int len=arr[i].size(); if(len == 0 && !respect[i]) ans.add(i); boolean flag=!respect[i]; for(int j=0;j<len;j++){ int num=arr[i].get(j); if(respect[num]) flag=false; dfs(num,arr,respect); } if(flag) ans.add(i); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
18595e9bd66cf6dcb99f1867338de87a
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.LinkedList; public class C_ { public static void main(String[] args) throws IOException { StreamTokenizer in = new StreamTokenizer(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); in.nextToken(); int n = (int) in.nval; int[] parent = new int[n]; int[] respect = new int[n]; for (int i = 0; i < n; i++) { in.nextToken(); parent[i] = (int) in.nval - 1; in.nextToken(); respect[i] = (int) in.nval; if (parent[i] == -2) parent[i] += 1; } int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = respect[i]; for (int i = 0; i < n; i++) if (parent[i] != -1) array[parent[i]] *= respect[i]; LinkedList<Integer> todel = new LinkedList<>(); for (int i = 0; i < n; i++) if (array[i] == 1) todel.addLast(i); if (todel.isEmpty()) out.print("-1"); else for (int i : todel) out.print(i + 1 + " "); out.flush(); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
1424b227bdffd6df7d07ea1d356227ab
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
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.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.StringTokenizer; public class hello2 {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 String sum (String s) { String s1 = ""; if(s.contains("a")) s1+="a"; if(s.contains("e")) s1+="e"; if(s.contains("i")) s1+="i"; if(s.contains("o")) s1+="o"; if(s.contains("u")) s1+="u"; return s1; } public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } public static void main(String args[]) { FastReader sc =new FastReader(); int n = sc.nextInt(); boolean[] visited = new boolean[n]; for(int i = 0; i<n; i++) { int par = sc.nextInt(); int respect = sc.nextInt(); if(respect==0) { visited[i] = true; if(par!=-1) visited[par-1] = true; } } boolean flag = false; for(int i = 0; i<n; i++) if(!visited[i]) { flag = true; System.out.print((i+1) + " "); } if(!flag) System.out.println(-1); } public static int dsu(int i,int j,char c[][],int ii,int jj,int visited[][],int n,int m,char c1) { int xa[] = {0,0,1,-1}; int ya[] = {1,-1,0,0}; visited[i][j] =1; for(int k=0;k<4;k++) { int newx = i + xa[k]; int newy = j + ya[k]; if(range(newx,newy,n,m)) { if(newx == ii && newy == jj) { continue; } if(visited[newx][newy]==1 && c[newx][newy]==c1) { return 1; } if(c[newx][newy]==c1) { dsu(newx,newy,c,i,j,visited,n,m,c1); } } } return 0; } public static boolean range(int x,int y,int n,int m) { if(x<0 || x>n-1 || y<0 || y>m-1) return false; return true; } static boolean find(int a[],int A,int B) { if( root(a,A)==root(a,B) ) //if A and B have the same root, it means that they are connected. return true; else return false; } static int union(int Arr[],int size[],int A,int B) { int root_A = root(Arr,A); int root_B = root(Arr,B); if(root_A == root_B) { return 1; } if(size[root_A] < size[root_B] ) { Arr[ root_A ] = Arr[root_B]; size[root_B] += size[root_A]; size[root_A] = 0; } else { Arr[ root_B ] = Arr[root_A]; size[root_A] += size[root_B]; size[root_B] = 0; } return 0; } static int root (int Arr[ ] ,int i) { while(Arr[ i ] != i) { i = Arr[ i ]; } return i; } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
a71c4b5feb62bc8889d027f175d99bff
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
// Working program with FastReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedWriter; import java.io.OutputStreamWriter; 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; } } public static void main(String[] args) { FastReader in=new FastReader(); int n = in.nextInt(); int relations[] = new int[n+1]; for(int i = 0;i<n; i++){ int p = in.nextInt(); int c = in.nextInt(); if(c == 0){ relations [i+1] = 1; if(p != -1){ relations[p] = 1; } } } try{ BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); boolean flag = false; for(int i = 1; i<n+1;i++){ if (relations[i] == 0) { flag = true; log.write(i + " "); } } if(!flag) log.write(-1 + ""); log.flush(); log.close(); }catch(IOException e){ } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
e029d026ca23aad98e9ecd7686ae0664
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class GFG { static ArrayList<Integer> adj[]; static HashMap<Integer,Integer> map; static PriorityQueue<Integer> pq=new PriorityQueue<>(); static int vis[]; static int p=0; static void dfs(int i) { vis[i] = 1; if((adj[i].size()!=0&&i!=p)&&map.get(i)==1){ int count=0,f=0; while(count<adj[i].size()){ if(map.get(adj[i].get(count))!=1){ f=1; break; } count++; } if(f==0){ pq.offer(i+1); } } else{ if(map.get(i)==1&&i!=p){ pq.offer(i+1); } } for(int j : adj[i]) { if(vis[j] == 0) dfs(j); } } ///////////////////////////////////////////////////////////////////////// public static void main (String[] args) { PrintWriter pw=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); p=0; adj = new ArrayList[n]; for(int i = 0; i < n; ++i) adj[i] = new ArrayList<>(); map=new HashMap<>(); for(int i=0;i<n;++i) { int v = sc.nextInt() - 1; map.put(i,sc.nextInt()); if(v>=0){ adj[v].add(i); // adj[i].add(v); } else{ p=i; } } vis = new int[n]; dfs(p); if(pq.size()==0) pw.println(-1); else{ while(pq.size()!=0) pw.print(pq.poll()+" "); } pw.close(); } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
ab6ea12d12b7509e63f444e2b57a3d59
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { InputStream inputStream = System.in; // InputStream inputStream = new FileInputStream(new File("input.txt")); OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } static class TaskA { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); List<Integer> parent = new ArrayList<>(n + 1); List<List<Integer>> children = new ArrayList<>(); boolean[] respected = new boolean[n + 1]; int[] disRespectedByChildren = new int[n + 1]; for (int i = 0; i <= n; i++) { children.add(new ArrayList<>()); respected[i] = true; parent.add(0); } for (int i = 1; i <= n; i++) { int p = in.nextInt(); int r = in.nextInt(); parent.set(i, p); if (p != -1) { children.get(p).add(i); } if (r == 1) { respected[i] = false; if (p != -1) disRespectedByChildren[p]++; } } boolean found = false; for (int i = 1; i <= n; i++) { if (!respected[i] && disRespectedByChildren[i] == children.get(i).size()) { found = true; // int p = parent.get(i); // disRespectedByChildren[p]--; // // for (int cIndex = 0; cIndex < children.get(p).size(); cIndex++) { // if (children.get(p).get(cIndex) == i) { // children.get(p).remove(cIndex); // break; // } // } // // for (int cIndex = 0; cIndex < children.get(i).size(); cIndex++) { // int child = children.get(i).get(cIndex); // children.get(p).add(child); // if (!respected[child]) disRespectedByChildren[p]++; // parent.set(child, p); // } out.print(i + " "); } } if (!found) { out.print("-1"); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
38d2f0abf3deb8a20987117e35a264dd
train_000.jsonl
1553965800
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int c[] = new int[n + 1]; int p[] = new int[n + 1]; boolean ok[] = new boolean[n + 1]; for (int i = 0; i < n; i++) { int x = sc.nextInt(); p[i + 1] = x; c[i + 1] = sc.nextInt(); if (c[i + 1] == 0) { ok[i + 1] = true; if (x != -1) { ok[x] = true; } } } int cnt = 0; for (int i = 1; i <= n; i++) { if (ok[i]) { continue; } if (cnt > 0) { System.out.print(" "); } cnt++; System.out.print(i); } if (cnt == 0) { System.out.print(-1); return; } } }
Java
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
1 second
["1 2 4", "-1", "5"]
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
Java 8
standard input
[ "dfs and similar", "trees" ]
1b975c5a13a2ad528b668a7c68c089f6
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
1,400
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
standard output
PASSED
6e1592f77f93a5815ef3ba2fb880516d
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.*; import java.util.*; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { File file = new File("in.txt"); InputStream inputStream = null; // try {inputStream= new FileInputStream(file);} catch (FileNotFoundException ex){return;}; 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.close(); } } class TaskB { Integer roadLength; Integer time; List<Integer> gasStations; public void solve(int testNumber, InputReader in, PrintWriter out) { Integer numberOfCars = in.nextInt(); Integer numberOfGasStations = in.nextInt(); roadLength = in.nextInt(); time = in.nextInt(); List<Integer> price = new ArrayList<>(numberOfCars); List<Integer> tankCapacity = new ArrayList<>(numberOfCars); gasStations = new ArrayList<>(numberOfGasStations+1); gasStations.add(0); for(int i=0; i<numberOfCars; i++){ price.add(in.nextInt()); tankCapacity.add(in.nextInt()); } for(int i=0; i<numberOfGasStations; i++){ gasStations.add(in.nextInt()); } gasStations.add(roadLength); gasStations.sort(Integer::compareTo); List<Integer> tankCopy = new ArrayList<>(tankCapacity); tankCopy.sort(Integer::compareTo); Integer min = 0; Integer max = tankCopy.size()-1; Integer mid = null; if(!willReach(tankCopy.get(max))){ out.println("-1"); return; } while(min<max){ mid = (min+max) / 2; if(willReach(tankCopy.get(mid))){ max = mid; } else{ min = mid+1; } } Integer capacityAtLeast = tankCopy.get(min); Integer minPrice = Integer.MAX_VALUE; for(int i=0; i<numberOfCars; i++){ if(tankCapacity.get(i) >= capacityAtLeast){ minPrice = Math.min(minPrice, price.get(i)); } } if(minPrice == Integer.MAX_VALUE){ out.println("-1"); } else { out.println(minPrice); } } public boolean willReach(Integer tankCapacity){ Integer timePassed = 0; for(int i=0; i<gasStations.size()-1; i++){ Integer dist = gasStations.get(i+1) - gasStations.get(i); if(dist>tankCapacity){ return Boolean.FALSE; } Integer timeOnFasterSpeed = Math.min(dist, (tankCapacity-dist)); timePassed += timeOnFasterSpeed + Math.max((dist - timeOnFasterSpeed)*2,0); } if(timePassed > time){ return Boolean.FALSE; } return Boolean.TRUE; } } 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 String nextLine(){ try { return reader.readLine(); } catch (IOException e){ throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } class Pair<F, S> { public final F first; public final S second; public Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.first, first) && Objects.equals(p.second, second); } @Override public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } @Override public String toString() { return "(" + first + ", " + second + ')'; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
7bf3eb4d277dda5bb43b4ce82e984e0e
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class _729_C_RoadToCinema { static ArrayList<Integer> gs; static int T; public static void main(String[] args) throws IOException { int N = readInt(), K = readInt(), M = readInt(); T = readInt(); int cst[] = new int[N+1], cap[] = new int[N+1]; for(int i = 1; i<=N; i++) {cst[i] = readInt(); cap[i] = readInt();} gs = new ArrayList<>(); gs.add(0); gs.add(M); for(int i = 1; i<=K; i++) gs.add(readInt()); Collections.sort(gs); int best = Integer.MAX_VALUE, lo = 1, hi = 1000000000; while(lo <= hi) { int mid = (lo + hi)/2; if(solve(mid)) {best = Math.min(best, mid); hi = mid - 1;} else lo = mid + 1; } int min = Integer.MAX_VALUE; for(int i = 1; i<=N; i++) if(cap[i] >= best) min = Math.min(min, cst[i]); println(min == Integer.MAX_VALUE ? -1 : min); exit(); } public static boolean solve(int cap) { long tot = 0; for(int i = 0; i<gs.size()-1; i++) { int delta = gs.get(i+1) - gs.get(i); if(cap < delta) return false; else if(cap >= 2*delta) tot += delta; else {int t = cap - delta; tot += 2*delta-t;} if(tot > T) return false; } if(tot > T) return false; return true; } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = Read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public static String read() throws IOException { byte[] ret = new byte[1024]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() throws IOException { int ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static long readLong() throws IOException { long ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static double readDouble() throws IOException { double ret = 0, div = 1; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (c == '.') { while ((c = Read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
3624aa1c9becb1ebd9569745f2792f07
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.*; import java.util.*; public class test { public static void main(String args[]) { //System.out.println("Welcome"); inputs in=new inputs(System.in); int n=in.nextInt(),k=in.nextInt(), s=in.nextInt(),t=in.nextInt(); car cars[]=new car[n]; for(int i=0;i<n;i++) { cars[i]=new car(in.nextInt(),in.nextInt()); } Arrays.sort(cars); int ks[]=new int[k]; for(int i=0;i<k;i++) { ks[i]=in.nextInt(); } Arrays.sort(ks); int d[]=new int[k+2]; d[0]=ks[0]; d[k]=s-ks[k-1]; d[k+1]=Integer.MAX_VALUE; for( int i=1;i<k;i++) { d[i]=ks[i]-ks[i-1]; } Arrays.sort(d); int fre=1,cd=d[0]; TreeSet<distance> set=new TreeSet<distance>(); set.add(new distance(0,0,0)); for(int i=1;i<=k+1;i++) { if(d[i]!=d[i-1]) { set.add(new distance(d[i-1],fre,cd)); } else { } cd+=d[i]; fre++; } /*for(distance q:set) { out(""+q.d+"---"+q.f+"----"+q.cd); } */ int j=-1; for(int i=0;i<n;i++) { if(d[k]>cars[i].v) continue; distance di=set.floor(new distance(cars[i].v/2,0,0)); int value=3*s-2*di.cd-(k+1-di.f)*cars[i].v; //out("i="+i+" value="+value+" cd="+di.cd+" f="+di.f+" k="+k+" v="+cars[i].v+" s="+s); if(value<=t) { j=i; break; } } if(j==-1) { out("-1"); return; } int ans=Integer.MAX_VALUE; for(int i=j;i<n;i++) { //out("i="+i); ans=Math.min(cars[i].c,ans); } out(""+ans); } static void out(String s) { System.out.println(s); } } class inputs { public BufferedReader reader; public StringTokenizer token; inputs(InputStream str) { reader=new BufferedReader(new InputStreamReader(str)); token=null; } int nextInt() { while(token==null||!token.hasMoreTokens()) { try { token=new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); } } return Integer.parseInt(token.nextToken()); } String next() { while(token==null||!token.hasMoreTokens()) { try { token=new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); } } return token.nextToken(); } } class car implements Comparable<car> { int c,v; car(int a,int b) { c=a; v=b; } public int compareTo(car z) { return this.v-z.v; } } class distance implements Comparable<distance> { int d,f,cd; distance(int a,int b,int c) { d=a; f=b; cd=c; } public int compareTo(distance a) { return this.d-a.d; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
d8b4f657d4024ee02e826f7ec1ae4f37
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
/** This is a solution to the problem Road To Cinema (729C) on codeforces.com * * Given: * - n cars with price c_i and fuel tank volume v_i * - k gas stations along a road of length s, at given positions * - timelimit t * * Fuel stations are free and instant. Each car has two speeds: 2min/km with 1l/km, and 1min/km with 2l/km. Speed can be changed any time. Cars are fully tanked. * What is the cheapest car with which the road can be passed in time? * * For details, see: * http://codeforces.com/problemset/problem/729/C */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class RoadToCinema { /* * Ideas: if s > t, print -1 (not possible) * As the speed can be changed any time, every average speed a, 1/km <= a <= 2/km is possible, with corresponding fuel usage (3 - a) / km * Sort cars by tank volume, sort gas stations by position. O(n log n) O(k log k) * Keep two pointers, one to car with minimum possible tank volume, on to car with maximum possible tank volume.? * Iterate through stations. Very every car between the first one able to make it and the first one able to make it at full speed: * update the minimum time required to get there. * If timelimit is exceeded OR cars are not able to make it at slow speed, increase first pointer. * If cars are not able to make it at full speed, increase second pointer. O(n*k) * Print cheapest car in range O(n) * * Better: Sort cars and stations, binary search on cars to get smallest volume car which gets there in time. O(n log n + k log k + k log n) * * O(k) possible? for each distance, compute range [minvolume, maxvolume], with corresponding times [mintime, maxtime], do same as above without the cars. Possible? */ private static class Car implements Comparable<Car> { public int price; public int volume; Car(int p, int v) { price = p; volume = v; } @Override public int compareTo(Car o) { return this.volume - o.volume; } } private boolean isInTime(int volume, List<Integer> stations, int length, int timeLimit) { int cur = 0; int k = stations.size(); int time = 0; for(int i = 0; i < k; ++i) { int dist = stations.get(i) - cur; if(dist > volume) return false; // not able to make this distance, even at slow speed else if(2*dist <= volume) time += dist; // can make it at full speed, then do it else { // dist <= volume < 2*dist -> spend volume/dist liters per km at average speed of (3 - volume/dist) time += 3*dist - volume; } if(time > timeLimit) return false; cur = stations.get(i); } return true; } private void solve() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader br = new BufferedReader(new FileReader("input.txt")); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int s = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); // read cars List<Car> cars = new ArrayList<Car>(n); for(int i = 0; i < n; ++i) { st = new StringTokenizer(br.readLine()); int p = Integer.parseInt(st.nextToken()); int v = Integer.parseInt(st.nextToken()); cars.add(new Car(p, v)); } // read stations st = new StringTokenizer(br.readLine()); List<Integer> stations = new ArrayList<Integer>(k); for(int i = 0; i < k; ++i) { stations.add(Integer.parseInt(st.nextToken())); } br.close(); Collections.sort(cars); Collections.sort(stations); stations.add(s); // binary search on cars to get FIRST car which can do it in time int left = 0; int right = n; while(left < right) { // invariant: the last item for which property does not hold is in [left, right) int mid = (left + right)/2; if(isInTime(cars.get(mid).volume, stations, s, t)) { // first must be on the left right = mid; } else { left = mid + 1; // first must be on the right } } int pos = right; if(pos >= n) System.out.println("-1"); else { int minPos = pos; for(pos++; pos < n; ++pos) { if(cars.get(minPos).price > cars.get(pos).price) { minPos = pos; } } System.out.println(cars.get(minPos).price); } } public static void main(String[] args) throws IOException { new RoadToCinema().solve(); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
6e49d8378c51615042e9fd27f5686b69
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class Solution { static class Solver { FastScanner scanner; PrintWriter out; List<Integer> result; Solver() { scanner = new FastScanner(System.in); out = new PrintWriter(System.out); result = new LinkedList<Integer>(); } public void solve() { int n = scanner.nextInt(); int k = scanner.nextInt(); int s = scanner.nextInt(); int t = scanner.nextInt(); Car[] cars = new Car[n]; for(int i = 0; i < n; i++) { cars[i] = new Car(scanner.nextInt(), scanner.nextInt()); } int[] p = new int[k]; for(int i = 0; i < k; i++) { p[i] = scanner.nextInt(); } Arrays.sort(cars); Arrays.sort(p); int low = 0; int high = n-1; int minC = -1; while(low <= high) { int m = (low+high)/2; if(canReach(cars[m], p, s, t)) { minC = m; high = m-1; } else { low = m+1; } } if(minC == -1) { out.println(-1); out.flush(); return; } int minCost = cars[minC].c; for(int i = minC+1; i < n; i++) { minCost = Math.min(minCost, cars[i].c); } out.println(minCost == Integer.MAX_VALUE ? -1 : minCost); out.flush(); } public boolean canReach(Car car, int[] k, int s, int t) { int time = 0; for(int i = 0; i <= k.length; i++) { //int d = i < k.length ? (i == 0 ? k[i] : (k[i] - k[i-1])) : (s - k[i-1]); int d = (i < k.length ? k[i] : s) - (i > 0 ? k[i-1] : 0); int modeA = Math.min(d, car.v - d); int modeS = d - modeA; if(modeA < 0) return false; time += modeA + (modeS*2); //System.out.println(car.c + ", " + d + ", " + time); } if(time > t) return false; return true; } public class Car implements Comparable<Car>{ int c; int v; public Car(int c, int v) { this.c = c; this.v = v; } public int compareTo(Car anotherCar) { return this.v - anotherCar.v; } } } public static void main(String[] args) throws IOException{ (new Solver()).solve(); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch(Exception e) { e.printStackTrace(); } } boolean hasNextToken() { if(st == null) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { } } return st.hasMoreTokens(); } String next() { while(st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() throws IOException{ return br.readLine(); } byte nextByte() { return Byte.parseByte(next()); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
17d972d50d2f930060e74e5e7c3c1ac8
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static final String NL = "\n"; public static final String SP = " "; public void append(StringBuffer sb, int[] arr) { for (int val: arr) { sb.append(val); sb.append(" "); } sb.append(NL); } public void append(StringBuffer sb, String... strs) { for (String str: strs) { sb.append(str); sb.append(" "); } sb.append(NL); } int time(int k, int s) { if (k >= 2 * s) return s; return (k - s) + 2 * (2 * s - k); } int time(int k, int[] g, int S) { int t = time(k, g[0]); for (int i = 1; i < g.length; i++) { t += time(k, g[i] - g[i - 1]); } t += time(k, S - g[g.length - 1]); return t; } public void run() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuffer sb = new StringBuffer(); String[] split = br.readLine().split(SP); int N = Integer.parseInt(split[0]); int M = Integer.parseInt(split[1]); int S = Integer.parseInt(split[2]); int T = Integer.parseInt(split[3]); int[] c = new int[N]; int[] v = new int[N]; for (int i = 0; i < N; i++) { split = br.readLine().split(SP); c[i] = Integer.parseInt(split[0]); v[i] = Integer.parseInt(split[1]); } int[] g = new int[M]; split = br.readLine().split(SP); for (int i = 0; i < M; i++) { g[i] = Integer.parseInt(split[i]); } Arrays.sort(g); int l = g[0]; for (int i = 1; i < M; i++) { l = Math.max(l, g[i] - g[i - 1]); } l = Math.max(S - g[M - 1], l); int r = 2 * l; int m; while (l + 1 < r) { m = l + (r - l) / 2; int t = time(m, g, S); if (t <= T) { // oil too much r = m; } else if (t > T) { l = m; } } int bound = time(l, g, S) <= T ? l : time(r, g, S) <= T ? r : Integer.MAX_VALUE; int res = -1; for (int i = 0; i < N; i++) { if (v[i] >= bound) { if (res == -1) { res = c[i]; } else { res = Math.min(res, c[i]); } } } append(sb, String.valueOf(res)); bw.write(sb.toString()); bw.flush(); bw.close(); br.close(); } public static void main(String[] args) throws IOException { new Solution().run(); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
698b39bdf99ff8cdbc4597b7af581b4c
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static final String NL = "\n"; public static final String SP = " "; public void append(StringBuffer sb, int[] arr) { for (int val: arr) { sb.append(val); sb.append(" "); } sb.append(NL); } public void append(StringBuffer sb, String... strs) { for (String str: strs) { sb.append(str); sb.append(" "); } sb.append(NL); } int time(int k, int s) { if (k >= 2 * s) return s; return (k - s) + 2 * (2 * s - k); } int time(int k, int[] g, int S) { int t = time(k, g[0]); for (int i = 1; i < g.length; i++) { t += time(k, g[i] - g[i - 1]); } t += time(k, S - g[g.length - 1]); return t; } public void run() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuffer sb = new StringBuffer(); String[] split = br.readLine().split(SP); int N = Integer.parseInt(split[0]); int M = Integer.parseInt(split[1]); int S = Integer.parseInt(split[2]); int T = Integer.parseInt(split[3]); int[] c = new int[N]; int[] v = new int[N]; for (int i = 0; i < N; i++) { split = br.readLine().split(SP); c[i] = Integer.parseInt(split[0]); v[i] = Integer.parseInt(split[1]); } int[] g = new int[M]; split = br.readLine().split(SP); for (int i = 0; i < M; i++) { g[i] = Integer.parseInt(split[i]); } Arrays.sort(g); int l = g[0]; for (int i = 1; i < M; i++) { l = Math.max(l, g[i] - g[i - 1]); } l = Math.max(S - g[M - 1], l); int r = 2 * l; int m; while (l + 1 < r) { m = l + (r - l) / 2; int t = time(m, g, S); if (t <= T) { // oil too much r = m; } else if (t > T) { l = m; } } int bound = time(l, g, S) <= T ? l : time(r, g, S) <= T ? r : Integer.MAX_VALUE; int res = -1; for (int i = 0; i < N; i++) { if (v[i] >= bound) { if (res == -1) { res = c[i]; } else { res = Math.min(res, c[i]); } } } append(sb, String.valueOf(res)); bw.write(sb.toString()); bw.flush(); bw.close(); br.close(); } public static void main(String[] args) throws IOException { new Solution().run(); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
203cf1b624f0f2158e36f3d92a23d3be
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class D{ public static void main(String[] args) throws Exception{ BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); String str = sc.readLine(); StringBuffer myBuff = new StringBuffer(); int n = Integer.parseInt(str.split(" ")[0]); int k = Integer.parseInt(str.split(" ")[1]); int s = Integer.parseInt(str.split(" ")[2]); int t = Integer.parseInt(str.split(" ")[3]); int[] c = new int[n]; int[] v = new int[n]; for(int i = 0; i < n; i++){ String[] strs = sc.readLine().split(" "); c[i] = Integer.parseInt(strs[0]); v[i] = Integer.parseInt(strs[1]); } int[] g_raw = new int[k + 1]; String[] strs = sc.readLine().split(" "); for(int i = 0; i < k; i++){ g_raw[i] = Integer.parseInt(strs[i]); } g_raw[k] = s; Arrays.sort(g_raw); int[] g = new int[k + 1]; for(int i = 0; i < k + 1; i++){ if(i == 0) g[i] = g_raw[i]; else g[i] = g_raw[i] - g_raw[i - 1]; } Arrays.sort(g); long oil = bin_search(g, (long) (g[k]), (long) (2 * g[k]), t); // System.out.println(oil); if(valid_t(g, oil) > t){ myBuff.append(-1); } else { int min_val = Integer.MAX_VALUE; for(int i = 0; i < n; i++){ if(v[i] >= oil){ min_val = Math.min(min_val, c[i]); } } if(min_val == Integer.MAX_VALUE) min_val = -1; myBuff.append(min_val); } out.write(myBuff.toString()); out.flush(); } private static long bin_search(int[] g, long low, long high, int t){ long mid = (low + high) / 2; int v = valid_t(g, mid); while(low < high){ mid = (low + high) / 2; v = valid_t(g, mid); // System.out.println("mid, v, t: " + mid + ", " + v + ", " + t); if(v < t) high = mid; else if(v > t) low = mid + 1; else{ return mid; } } return low; } private static int valid_t(int[] g, long oil){ int t = 0; for(int i = 0; i < g.length; i++){ int val = 0; if(oil >= 2 * g[i]){ t += g[i]; } else { t += (int) ((oil - g[i]) + (2 * g[i] - oil) * 2); } } return t; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
df7f33e2a74173c42fb80f316eea282b
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.*; public class Third{ static long mod=1000000007; public static void main(String[] args) throws Exception{ InputReader in = new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); //int t=in.readInt(); //while(t-->0) //{ int n=in.readInt(); int k=in.readInt(); int s=in.readInt(); int t=in.readInt(); //long n=in.readLong(); int c[]=new int[n]; int v[]=new int[n]; for(int i=0;i<n;i++) { c[i]=in.readInt(); v[i]=in.readInt(); } int g[]=new int[k+1]; for(int i=0;i<k;i++) g[i]=in.readInt(); g[k]=s; Arrays.sort(g); int pos=1; int f=1; int l=(int)mod; int ans=-1; int mintime=-1; while(f<=l) { int m=f+l; m/=2; //System.out.println(m); int x=m; int time=0; int p=1; for(int i=0;i<=k;i++) { int y=g[i]; if(i-1>=0) y-=g[i-1]; //System.out.println(y); if(y>x) { p=0; break; } else { int f1=0; int l1=y; int good=-1; while(f1<=l1) { int m1=f1+l1; m1/=2; //System.out.println(m1+" "+y); int rem=y-m1; int cons=2*m1+rem; //if(m==5) //System.out.println(cons+" "+x+" "+m+" "+y+" "+m1); if(cons<=x) { good=m1; //System.out.println(good); f1=m1+1; } else { l1=m1-1; } } //System.out.println(good+" "+m+" "+y); if(good==-1) { //System.out.println(m); p=0; break; } else { int rem=y-good; int tt=good+rem*2; time+=tt; } //System.out.println(m+" "+time+" "+good+" "+m+" "+p); } if(time>t) { //System.out.println(m+" "+time); break; } } //System.out.println(m+" "+p+" "+time); if(p==1&&time<=t) { ans=m; //System.out.println(ans); l=m-1; } else { f=m+1; } } if(ans==-1) pw.println(ans); else { int min=(int)mod; //System.out.println(ans); for(int i=0;i<n;i++) { if(v[i]>=ans) { min=min(min,c[i]); } } if(min==(int)mod) pw.println(-1); else pw.println(min); } //} pw.close(); } public static long gcd(long x,long y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int abs(int a,int b) { return (int)Math.abs(a-b); } public static long abs(long a,long b) { return (long)Math.abs(a-b); } public static int max(int a,int b) { if(a>b) return a; else return b; } public static int min(int a,int b) { if(a>b) return b; else return a; } public static long max(long a,long b) { if(a>b) return a; else return b; } public static long min(long a,long b) { if(a>b) return b; else return a; } 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; } public static long pow(long n,long p) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static class Pair implements Comparable<Pair> { int a,b; Pair (int a,int b) { this.a=a; this.b=b; } public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.a!=o.a) return Integer.compare(this.a,o.a); else return Integer.compare(this.b, o.b); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.a == a && p.b == b; } return false; } public int hashCode() { return new Integer(a).hashCode() * 31 + new Integer(b).hashCode(); } } 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 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; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String readLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //StringBuilder sb=new StringBuilder(""); //InputReader in = new InputReader(System.in); //PrintWriter pw=new PrintWriter(System.out); //String line=br.readLine().trim(); //int t=Integer.parseInt(br.readLine()); // while(t-->0) //{ //int n=Integer.parseInt(br.readLine()); //long n=Long.parseLong(br.readLine()); //String l[]=br.readLine().split(" "); //int m=Integer.parseInt(l[0]); //int k=Integer.parseInt(l[1]); //String l[]=br.readLine().split(" "); //l=br.readLine().split(" "); /*int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(l[i]); }*/ //System.out.println(" "); //} }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
d58ef231653f2592a14068b4589204e2
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import javafx.util.Pair; import java.io.*; import java.util.Arrays; public class Main { private static myScanner sc; private static PrintWriter pw; private static final boolean defaultInAndOutPut = true; private static final int numberOfTests = 1; private static final String nameOfInAndOutFile = ""; private static final String fullNameInputFile = nameOfInAndOutFile + ".in"; private static final String fullNameOutputFile = nameOfInAndOutFile + ".out"; public static void main(String[] args) throws IOException { if (defaultInAndOutPut) { setDefaultInAndOutPut(); } else { setInAndOutPutFromFile(); } for (int test = 1; test <= numberOfTests; test++) { solve(); pw.flush(); } pw.close(); } private static void setDefaultInAndOutPut() { sc = new myScanner(new BufferedReader(new InputStreamReader(System.in))); pw = new PrintWriter(System.out); } private static void setInAndOutPutFromFile() throws IOException { sc = new myScanner(new BufferedReader(new FileReader(new File(fullNameInputFile)))); pw = new PrintWriter(new File(fullNameOutputFile)); } private static final int intINF = Integer.MAX_VALUE; private static final int MOD = 1000000007; private static final long longINF = Long.MAX_VALUE; private static void solve() { int n = sc.nextInt(), k = sc.nextInt(), s = sc.nextInt(), t = sc.nextInt(); Pair<Integer, Integer>[] cars = new Pair[n]; for (int i = 0; i < n; i++) cars[i] = new Pair(sc.nextInt(), sc.nextInt()); int[] g = sc.nextArrayInts(k); Arrays.sort(g); int last = 0; int[] distance = new int[k+1]; for (int i = 0; i < k; i++) { distance[i] = g[i] - last; last = g[i]; } distance[k]=s-last; int min = 0, max = 1000000001; while (max - min > 1) { int mid = (max + min) / 2; if (spend(mid, k+1, distance) > t) min = mid; else max = mid; } int ans = intINF; for (int i = 0; i < n; i++) { if (cars[i].getValue() >= max) ans = Math.min(ans, cars[i].getKey()); } pw.print(ans==intINF?-1:ans); } private static int spend(int mid, int k, int[] distance) { int time = 0; for (int d : distance) { if (d > mid) return intINF; time += d + d; time -= Math.min(d,mid - d); } return time; } } class myScanner { private char[] buffer = new char[1 << 8]; private int pos = 1; private BufferedReader reader; public myScanner(BufferedReader reader) { this.reader = reader; } public boolean hasNext() { return pos > 0; } private void loadBuffer() { pos = 0; try { for (int i; (i = reader.read()) != -1; ) { char c = (char) i; if (c != ' ' && c != '\n' && c != '\t' && c != '\r' && c != '\f') { if (pos == buffer.length) buffer = Arrays.copyOf(buffer, 2 * pos); buffer[pos++] = c; } else if (pos != 0) break; } } catch (IOException e) { throw new UncheckedIOException(e); } } public String current() { return String.copyValueOf(buffer, 0, pos); } public String next() { loadBuffer(); return current(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new UncheckedIOException(e); } } public int nextInt() { return nextInt(10); } public long nextLong() { return nextLong(10); } public int nextInt(int radix) { loadBuffer(); int result = 0; int i = buffer[0] == '-' || buffer[0] == '+' ? 1 : 0; for (checkValidNumber(pos > i); i < pos; i++) { int digit = buffer[i] - '0'; checkValidNumber(0 <= digit && digit <= radix - 1); result = result * radix + digit; } return buffer[0] == '-' ? -result : result; } public long nextLong(int radix) { loadBuffer(); long result = 0; int i = buffer[0] == '-' || buffer[0] == '+' ? 1 : 0; for (checkValidNumber(pos > i); i < pos; i++) { int digit = buffer[i] - '0'; checkValidNumber(0 <= digit && digit <= radix - 1); result = result * radix + digit; } return buffer[0] == '-' ? -result : result; } public int[] nextArrayInts(int size) { int[] input = new int[size]; for (int i = 0; i < size; i++) input[i] = nextInt(); return input; } public long[] nextArrayLongs(int size) { long[] input = new long[size]; for (int i = 0; i < size; i++) input[i] = nextLong(); return input; } public double nextDouble() { loadBuffer(); long result = 0; int i = buffer[0] == '-' || buffer[0] == '+' ? 1 : 0; long round = 1; final int radix = 10; boolean hasPoint = false; for (checkValidNumber(pos > i); i < pos; i++) { int digit = buffer[i] - '0'; checkValidNumber((0 <= digit && digit <= radix - 1) || (!hasPoint && digit == -2)); if (digit == -2) hasPoint = true; else { if (hasPoint) round *= radix; result = result * radix + digit; } } return buffer[0] == '-' ? -result / (1.0 * round) : result / (1.0 * round); } private void checkValidNumber(boolean condition) { if (!condition) throw new NumberFormatException(current()); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
195023272cf0732c8111df89f3e0f919
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.*; import java.util.*; public class Main { 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); } } 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()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String s=""; try { s=br.readLine(); } catch(IOException e) { e.printStackTrace(); } return s; } Long nextLong() { return Long.parseLong(next()); } } static class Car implements Comparable<Car> { long c; long v; public Car(long c,long v) { this.c=c; this.v=v; } public int compareTo(Car k) { if(v==k.v) return 0; else { if(v>k.v) return 1; else return -1; } } } public static void main(String ar[]) { InputReader s=new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); int n=s.nextInt(); int k=s.nextInt(); long d=s.nextLong(); long t=s.nextLong(); ArrayList<Car> a=new ArrayList<Car>(); for(int j=0;j<n;j++) a.add(new Car(s.nextLong(),s.nextLong())); Collections.sort(a); int g[]=new int[k+1]; for(int j=1;j<=k;j++) g[j]=s.nextInt(); Arrays.sort(g); //System.out.println("hello 1"); int gd[]=new int[k+2]; for(int j=1;j<=k;j++) { //int temp=s.nextInt(); gd[j]=g[j]-g[j-1]; //System.out.println("j== "+j+" gd[j] = = "+gd[j]); //lastg=temp; } gd[k+1]=(int)d-g[k]; //for(int p=1;p<=k+1;p++) // System.out.print(gd[p]+" " ); int lastg=0; int l=0,r=n-1; int mid=(l+r)/2; int minmid=-1; while(l<=r) { mid=(l+r)/2; long t1=0; int x; for( x=1;x<=k+1;x++) { long temp=Math.round(Math.min(gd[x],(int)(a.get(mid).v-gd[x]))); if(temp<0) break; t1+=2*gd[x]-temp; } if(t1>t || x!=k+2 ) l=mid+1; else { //System.out.println("the following capacity satisfied "+a.get(mid).v + "with t1 = = "+t1); minmid=mid; r=mid-1 ; } } // System.out.println("minimum capacity "+a.get(minmid).v); long mincost=Long.MAX_VALUE; if(minmid==-1) out.print("-1"); else { for(int j=minmid;j<n;j++) mincost=Math.min(mincost,a.get(j).c); out.print(mincost); } /*int g[]=new int[k+1]; for(int j=1;j<=k;j++) g[j]=s.nextInt(); Arrays.sort(g); //for(int p=1;p<=k;p++) // System.out.print(g[p]+" " ); for(int j=1;j<=k;j++) { //int temp=s.nextInt(); gd[j]=g[j]-g[j-1]; //System.out.println("j== "+j+" gd[j] = = "+gd[j]); //lastg=temp; } //System.out.println("hello 2"); gd[k+1]=(int)d-g[k]; Arrays.sort(gd); //for(int p=1;p<=k+1;p++) // System.out.print(gd[p]+" " ); //System.out.println(); for(int j=n-1;j>=0;j--) { //System.out.println(" a(j) = = = "+a.get(j).v+" gd[k+1] = = "+gd[k+1] ); if(a.get(j).v<gd[k+1]) { // System.out.println("removing = == = "+ j); a.remove(j); } } int j; for( j=0;j<a.size();j++) { long t1=0; for(int x=1;x<=k+1;x++) t1+=2*gd[x]-Math.round(Math.min(gd[x],(int)(a.get(j).v-gd[x]))); // out.println(a.get(j).c+" " +t1); if(t1<=t) { out.print(a.get(j).c); break; } } if(j==a.size()) out.print("-1");*/ out.close(); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
5b6c07a676d40527b4cdf1013483bdf6
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Solution { static boolean bigEnough(int w, int t, int[] distance) { long time = 0; for (int aDistance : distance) if (aDistance > w) return false; else if (w >= 2 * aDistance) time += aDistance; else time += 3 * aDistance - w; return time <= t; } static int binary(int left, int right, int t, int[] distance) { while (right - left > 1) { int w = (left + right) / 2; if (bigEnough(w, t, distance)) right = w; else left = w; } return right; } public static void main(String[] args) { MyScanner in = new MyScanner(); int n = in.nextInt(); int k = in.nextInt(); int s = in.nextInt(); int t = in.nextInt(); int[] ci = new int[n]; int[] vi = new int[n]; int vmax = 0; for (int i = 0; i < n; i++) { ci[i] = in.nextInt(); vi[i] = in.nextInt(); vmax = Math.max(vi[i], vmax); } int g[] = new int[k]; for (int i = 0; i < k; i++) { g[i] = in.nextInt(); } Arrays.sort(g); int distance[] = new int[k + 1]; distance[0] = g[0]; for (int i = 1; i < k; i++) { distance[i] = g[i] - g[i - 1]; } distance[k] = s - g[k - 1]; if (!bigEnough(vmax, t, distance)) { System.out.println(-1); return; } int w = binary(0, vmax, t, distance); int cmin = -1; for (int i = 0; i < n; i++) { if (vi[i] >= w && (cmin == -1 || cmin > ci[i])) { cmin = ci[i]; } } System.out.println(cmin); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
63fb2550bbb89ce1e3899c6797dfecd2
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Codeforcecontest { int n,k,s,t; int arr[]; 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 void main(String[] args) throws IOException { //Scanner s = new Scanner(System.in); Codeforcecontest con = new Codeforcecontest(); con.run(); } class pair{ int price,fuel; public pair(int pr,int fl){ price = pr; fuel = fl; } } private void run() { FastReader fr = new FastReader(); n = fr.nextInt(); k = fr.nextInt(); s = fr.nextInt(); t = fr.nextInt(); pair ax[] = new pair[n]; for(int i=0;i<n;i++) { ax[i] = new pair(fr.nextInt(), fr.nextInt()); } arr = new int[k+2]; // arr[0] = 0; // arr[k+1] = s; for(int i=0;i<k;i++) arr[i] = fr.nextInt(); arr[k] = 0; arr[k+1] = s; Arrays.sort(arr); int len = findcap(); if(len==-1) System.out.println(-1); else{ int price = Integer.MAX_VALUE; for(int i=0;i<n;i++) { if(ax[i].fuel>=len) price = Math.min(price, ax[i].price); } System.out.println((price==Integer.MAX_VALUE)?-1:price); } } private int findcap() { int incap = 1; int finalcap = (int) (1e9 + 1); int ans = -1; while(incap<=finalcap) { int mid= (incap+finalcap)/2; if(check(mid)) { ans = mid; finalcap = mid-1; } else incap = mid+1; } return ans; } private boolean check(int fuel) { boolean flag = true; int x = arr[0]; int time = 0; for(int i=1;i<arr.length;i++) { int y = arr[i]; int d = y-x; if(d>fuel) { flag = false; break; } int temp = 2*d; int remf = fuel - d; temp-=Math.min(remf, d); time+=temp; x = y; } if(!flag) return false; else return (time<=t)?true:false; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
a39a1af88e6ce0709a6f65a06d4fd91a
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author cunbidun */ 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); CRoadToCinema solver = new CRoadToCinema(); solver.solve(1, in, out); out.close(); } static class CRoadToCinema { private int[] gas; private int k; private int s; private int t; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); k = in.nextInt(); s = in.nextInt(); t = in.nextInt(); PairII[] car = new PairII[n + 1]; for (int i = 1; i <= n; i++) { car[i] = new PairII(in.nextInt(), in.nextInt()); } gas = in.nextIntArray(k, 1); Arrays.sort(car, 1, n + 1); MergeSort.sort(gas, 1, k); int[] maxGas = new int[n + 1]; maxGas[1] = car[1].second; for (int i = 2; i <= n; i++) { maxGas[i] = MaxMin.Max(maxGas[i - 1], car[i].second); } int l = 1, r = n; while (l != r) { if (l == r - 1) { if (!ch(maxGas[l])) l = r; break; } int m = (l + r) >> 1; if (ch(maxGas[m])) r = m; else l = m + 1; } if (!ch(maxGas[l])) { out.println(-1); return; } out.println(car[l].first); } private boolean ch(int m) { int cur = 0; int time = 0; for (int i = 1; i <= k; i++) { int d = gas[i] - cur; if (d > m) return false; else if (m >= 2 * d) time += d; else { int acc = m - d; int nor = d - acc; time += acc + nor * 2; } cur = gas[i]; } int d = s - cur; if (d > m) return false; else if (m >= 2 * d) time += d; else { int acc = m - d; int nor = d - acc; time += acc + nor * 2; } return time <= t; } } static class MergeSort { public static void sort(int[] list, int lowIndex, int highIndex) { if (lowIndex != highIndex) { int midIndex = (lowIndex + highIndex) / 2; sort(list, lowIndex, midIndex); sort(list, midIndex + 1, highIndex); merge(list, lowIndex, midIndex, highIndex); } } private static void merge(int[] list, int lowIndex, int midIndex, int highIndex) { int[] L = new int[midIndex - lowIndex + 2]; if (midIndex + 1 - lowIndex >= 0) System.arraycopy(list, lowIndex, L, 0, midIndex + 1 - lowIndex); L[midIndex - lowIndex + 1] = Integer.MAX_VALUE; int[] R = new int[highIndex - midIndex + 1]; for (int i = midIndex + 1; i <= highIndex; i++) R[i - midIndex - 1] = list[i]; R[highIndex - midIndex] = Integer.MAX_VALUE; int i = 0, j = 0; for (int k = lowIndex; k <= highIndex; k++) if (L[i] <= R[j]) { list[k] = L[i]; i++; } else { list[k] = R[j]; j++; } } } static class PairII implements Comparable<PairII> { public int first; public int second; public PairII(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PairII pair = (PairII) o; return first == pair.first && second == pair.second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(PairII o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } static class InputReader extends InputStream { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int length, int stIndex) { int[] arr = new int[length + stIndex]; for (int i = stIndex; i < stIndex + length; i++) arr[i] = nextInt(); return arr; } private static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class MaxMin { public static <T extends Comparable<T>> T Max(T x, T y) { T max = x; if (y.compareTo(max) > 0) max = y; return max; } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
c0d0f22f3ef81f4df5ac7b4ed3e19b32
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
//package olymp_prog; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /** * Created by Максим on 26.12.2016. */ public class C729 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String raw[] = in.readLine().split(" "); int n = Integer.parseInt(raw[0]); int k = Integer.parseInt(raw[1]); int s = Integer.parseInt(raw[2]); int t = Integer.parseInt(raw[3]); int c[] = new int[n]; int v[] = new int[n]; for (int i = 0; i < n; i++) { raw = in.readLine().split(" "); c[i] = Integer.parseInt(raw[0]); v[i] = Integer.parseInt(raw[1]); } raw = in.readLine().split(" "); int g[] = new int[k + 2]; int len = k + 2; g[0] = 0; for (int i = 1; i < len - 1; i++) { g[i] = Integer.parseInt(raw[i - 1]); } g[len - 1] = s; Arrays.sort(g); int dists[] = new int[len]; dists[0] = 0; // System.out.println(Arrays.toString(g)); for (int i = 1; i < dists.length; i++) { dists[i] = g[i] - g[i - 1]; } Arrays.sort(dists); int d[] = new int[dists.length]; int sum = 0; for (int i = 0; i < d.length; i++) { sum += dists[i]; d[i] = sum; } int minC = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // det what is fast only if (dists[dists.length - 1] > v[i]) continue; int fast = 0; int slow = 0; int first = binarySearch(dists, v[i] / 2); // System.out.println("first = " + first); // System.out.println("v[i] / 2 = " + v[i] / 2); // System.out.println(Arrays.toString(dists)); fast += d[first]; // System.out.println("d[first] = " + d[first]); // det what is fast and slow int second = binarySearch(dists, v[i]); int tmp = (second - first) * v[i] - (d[second] - d[first]); // System.out.println("(dists[second] - dists[first]) = " + (dists[second] - dists[first])); // System.out.println("tmp = " + tmp); // System.out.println("second = " + second); fast += tmp; slow += d[second] - d[first] - tmp; slow += dists[dists.length - 1] - dists[second]; // System.out.println("fast = " + fast); // System.out.println("slow = " + slow); int curT = slow * 2 + fast; if (curT <= t) { minC = Math.min(minC, c[i]); } // System.out.println("curT = " + curT); // rest what is slow only } if (minC != Integer.MAX_VALUE) { System.out.println(minC); } else { System.out.println("-1"); } } public static int binarySearch(int a[], int tar) { int l = 0; int r = a.length - 1; while (l < r) { int m = (l + r) / 2; if (tar >= a[m]) { l = m; } else { r = m - 1; } if (r == l + 1) { if (tar >= a[r]) { l = r; } else { r = l; } } } return l; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
ac745cd7f4cd1bd6ffac2305a6076a71
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int k = sc.nextInt(); int s = sc.nextInt(); int t = sc.nextInt(); int[] c = new int[n]; int[] v = new int[n]; for (int i = 0; i < n; ++i){ c[i] = sc.nextInt(); v[i] = sc.nextInt(); } int[] arr = new int[k]; for (int i =0 ; i < k; ++i){ arr[i] = sc.nextInt(); } Arrays.sort(arr); int[] dis = new int[k+1]; int prev = 0; for (int i = 0; i < k; ++i){ int cur = arr[i]; dis[i] = cur - prev; prev = cur; } dis[k] = s - prev; Arrays.sort(dis); // Work int best = -1; int minNeed = 2000000000; int lo = 0, hi = 1000000000; while (lo <= hi){ int mid = lo + (hi - lo) / 2; int total = 0; for (int i = 0; i <= k; ++i){ if (mid < dis[i]){ total = t+1; break; } int turbo = Math.max(mid - dis[i], 0); turbo = Math.min(turbo, dis[i]); int rem = dis[i] - turbo; total += turbo + rem * 2; } //System.out.println(mid + " " + total); if (total <= t){ hi = mid - 1; minNeed = Math.min(minNeed, mid); }else{ lo = mid + 1; } } //System.out.println(minNeed); for (int i =0 ; i < n; ++i){ if (v[i] >= minNeed){ best = best == -1 ? c[i] : Math.min(best, c[i]); } } System.out.println(best); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
94d72b6ad9a309fb78c8d460d53004f1
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class C { static class Solver{ int n, k, s, t; int[] g; Car[] cars; public void solve(InputReader in, PrintWriter out) { read(in); Arrays.sort(cars); Arrays.sort(g); int l = 0, r = n-1, m, minVol = -1; while (l <= r) { m = (l+r)/2; if (isGood(cars[m])) { minVol = m; r = m-1; } else { l = m+1; } } if (minVol < 0) { out.println(-1); return; } int minCost = cars[minVol].cost; for (int i = minVol+1; i < n; ++ i) minCost = Math.min(minCost, cars[i].cost); out.println(minCost); } boolean isGood(Car car) { int time = 0, dist, acDist; // System.out.format("volume = %d%n", car.vol); for (int i = 0; i <= k; ++ i) { dist = (i < k ? g[i] : s) - (i > 0 ? g[i-1] : 0); acDist = Math.min(car.vol - dist, dist); // System.out.format("dist = %d, acDist = %d, time = %d%n", dist, acDist, time); if (acDist < 0) return false; time += acDist + (dist - acDist)*2; } return time <= t; } void read(InputReader in) { n = in.nextInt(); k = in.nextInt(); s = in.nextInt(); t = in.nextInt(); cars = new Car[n]; g = new int[k]; for (int i = 0; i < n; ++ i) { cars[i] = new Car(in.nextInt(), in.nextInt()); } for (int i = 0; i < k; ++ i) { g[i] = in.nextInt(); } } class Car implements Comparable<Car>{ int cost, vol; public Car(int c, int v) { cost = c; vol = v; } public int compareTo(Car other) { return this.vol - other.vol; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(in, out); out.close(); } static class InputReader{ BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
18a264e03e54f98ef23aa2c29dbd5f59
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Stack; public class Main{ public static void main(String[] args) throws IOException { String IN = "C:\\Users\\ugochukwu.okeke\\Desktop\\in.file"; String OUT = "C:\\Users\\ugochukwu.okeke\\Desktop\\out.file"; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String[] in= br.readLine().split(" "); int n=Integer.parseInt(in[0]),k=Integer.parseInt(in[1]),s=Integer.parseInt(in[2]),t=Integer.parseInt(in[3]); int[][] store = new int[n][2]; for(int i=0;i<n;i++) { in=br.readLine().split(" "); store[i][0] = Integer.parseInt(in[0]); store[i][1] = Integer.parseInt(in[1]); } int[] a = new int[k+2]; in=br.readLine().split(" "); for(int i=0;i<in.length;i++) { a[i+1]=Integer.parseInt(in[i]); } a[a.length-1] = s; Arrays.sort(a); int w = findBest(a, t); //System.out.println("best time is "+w); // System.exit(0); int ans = 1000000001; for(int i=0;i<n;i++) { if(store[i][1] >= w) { ans = Math.min(store[i][0], ans); } } if(ans == 1000000001) bw.append("-1\n"); else bw.append(ans+"\n"); bw.close(); //done then } private static int findBest(int[] a, int t) { int lo=0; int hi=1000000001; while(lo < hi) { int mid = lo+hi>>1; //: capacity in fuel //mid=9; //System.out.println("using fuel cap of "+mid); boolean bad = false; int totalTime = 0; for(int i=1;i<a.length;i++) { int d = a[i]-a[i-1]; if(d > mid){ bad = true; break; } else{ int k1 = Math.min(d, mid-d); int k2 = d-k1; //System.out.println(k1+" "+k2); totalTime += k1+2*k2; } if(totalTime > t) { bad=true; break; } } if(bad) lo=mid+1; else hi=mid; } return lo; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
aab94e9fb9ea41232eca291598cccdd3
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; /** * @author pvasilyev * @since 20 Nov 2016 */ public class C { public static void main(String[] args) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); final PrintWriter writer = new PrintWriter(System.out); solve(reader, writer); reader.close(); writer.close(); } private static void solve(final BufferedReader reader, final PrintWriter writer) throws IOException { String line = reader.readLine(); String[] split = line.split(" "); final int n = Integer.valueOf(split[0]); final int k = Integer.valueOf(split[1]); final int s = Integer.valueOf(split[2]); final int timeLimit = Integer.valueOf(split[3]); int[][] cars = new int[n][2]; for (int i = 0; i < cars.length; i++) { line = reader.readLine(); split = line.split(" "); cars[i][0] = Integer.valueOf(split[0]); cars[i][1] = Integer.valueOf(split[1]); } line = reader.readLine(); split = line.split(" "); Integer[] g = new Integer[k]; for (int i = 0; i < g.length; i++) { g[i] = Integer.valueOf(split[i]); } Arrays.sort(g); Integer[] distances = new Integer[k+1]; distances[0] = g[0]; for (int i = 1; i < g.length; ++i) { distances[i] = g[i] - g[i-1]; } distances[k] = s - g[k-1]; Arrays.sort(distances); long[] prefixSum = new long[distances.length+1]; for (int i = 1; i <= distances.length; ++i) { prefixSum[i] = prefixSum[i-1] + distances[i-1]; } int minRent = Integer.MAX_VALUE; for (int i = 0; i < n; ++i) { int volume = cars[i][1]; if (volume < distances[k]) { // this guy won't be able to pass the longest distance: he will be short of gasoline continue; } final long time; if (volume > 2 * distances[k]) { // this guy can run whole path in fast mode: time = s; } else { // at some point we can't afford fast mode and we need to turn on slow mode: final int position = binarySearch(distances, volume, 0, distances.length); final long timeInFastMode = prefixSum[position]; final long timeInSlowMode = ((prefixSum[prefixSum.length - 1] - prefixSum[position]) * 3 - (prefixSum.length -1 - position) * volume); time = timeInFastMode + timeInSlowMode; } boolean canRun = time <= timeLimit; if (canRun) { minRent = Math.min(minRent, cars[i][0]); } } if (minRent != Integer.MAX_VALUE) { writer.println(minRent); } else { writer.println(-1); } } /** * Should return the first position in <code>distances</code>, when we can't use fast mode for whole distance and we * should downgrade till slow mode to save some gasoline. * <p/> * I.e. the minimal index <code>i</code>, such as: 2 * <code>distances[i]</code> &gt; <code>volume</code>. */ private static int binarySearch(final Integer[] distances, final int volume, final int start, final int end) { if (end - start < 1) { return start; } else if (2 * distances[start] > volume) { return start; } else { final int mid = (start + end) / 2; if (2 * distances[mid] <= volume) { return binarySearch(distances, volume, mid+1, end); } else { return binarySearch(distances, volume, start, mid); } } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
6ea232ab5dc500c6caff45c54886f76b
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class RoadToCinema { static int n, k, s, t; static int c[], v[], g[]; static boolean flag; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String line = in.readLine(); StringTokenizer st; st = new StringTokenizer(line); n = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); s = Integer.parseInt(st.nextToken()); t = Integer.parseInt(st.nextToken()); c = new int[n]; v = new int[n]; g = new int[k + 2]; for (int i = 0; i < n; i++) { st = new StringTokenizer(in.readLine()); c[i] = Integer.parseInt(st.nextToken()); v[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(in.readLine()); for (int i = 1; i <= k; i++) { g[i] = Integer.parseInt(st.nextToken()); } g[0] = 0; g[k + 1] = s; k += 2; Arrays.sort(g); flag = false; long l = 0, r = s * 2, mid; while (l < r) { mid = (l + r) / 2; if (can(mid)) { r = mid; } else { l = mid + 1; } } if (!flag) { out.println(-1); } else { int ans = (int) 1e9 + 10; for (int i = 0; i < n; i++) { if (v[i] >= l) { ans = Math.min(ans, c[i]); } } if (ans == (int) 1e9 + 10) { out.println(-1); } else { out.println(ans); } } out.close(); in.close(); } static boolean can(long mid) { long time = 0; for (int i = 1; i < k; ++i) { long dix = g[i] - g[i - 1]; if (dix > mid) return false; long fv = (mid - dix) * 2; long sv = mid - fv; if (sv < 0) time += dix; else time += fv / 2 + sv * 2; } if (time <= t) { flag = true; return true; } else return false; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
004ce8ea158cd5007ee27a10040fd4ff
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import static java.lang.Math.min; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; public class Main { private FastScanner in; private PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), k = in.nextInt(); long s = in.nextLong(), t = in.nextLong(); if (t < s) { out.println(-1); return; } long[] c = new long[n], v = new long[n]; for (int i = 0; i < n; i++) { c[i] = in.nextLong(); v[i] = in.nextLong(); } ArrayList<Long> g = new ArrayList<>(k); g.add((long) 0); for (int i = 0; i < k; i++) g.add(in.nextLong()); g.add(s); sort(g); k++; for (int i = 0; i < k; i++) g.set(i, g.get(i + 1) - g.get(i)); g.remove(k); sort(g, reverseOrder()); int i = 0; long sum = 0, x = min(t - s, s); for (; i < k; i++) { if (sum >= x + g.get(i) * i) break; sum += g.get(i); } long ans = -1; long V = (i > 0 ? ((sum - x + i - 1) / i) : g.get(0)) + g.get(0); for (int j = 0; j < n; j++) if (v[j] >= V) ans = ans == -1 ? c[j] : min(ans, c[j]); out.println(ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // in = new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
9069f85d32bfe9b64ceb14b3e94e336b
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import static java.lang.Math.min; import static java.util.Collections.sort; public class Main { private FastScanner in; private PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), k = in.nextInt(); long s = in.nextLong(), t = in.nextLong(); if (t < s) { out.println(-1); return; } long[] c = new long[n], v = new long[n]; for (int i = 0; i < n; i++) { c[i] = in.nextLong(); v[i] = in.nextLong(); } ArrayList<Long> g = new ArrayList<>(k); g.add((long) 0); for (int i = 0; i < k; i++) g.add(in.nextLong()); g.add(s); sort(g); k++; for (int i = 0; i < k; i++) g.set(i, g.get(i + 1) - g.get(i)); g.remove(k); sort(g, Collections.reverseOrder()); int i = 0; long sum = 0, x = min(t - s, s); for (; i < k; i++) { sum += g.get(i); if (sum >= x + g.get(i) * (long) (i + 1)) break; } if (i < k) sum -= g.get(i); long ans = -1; long V = (i > 0 ? ((sum - x + i - 1) / (long) i) : g.get(0)) + g.get(0); for (int j = 0; j < n; j++) if (v[j] >= V) ans = ans == -1 ? c[j] : min(ans, c[j]); out.println(ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // in = new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
743eea8a5dedda610c59ff7eb517fa8b
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import static java.lang.Math.min; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; public class Main { private FastScanner in; private PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), k = in.nextInt(); long s = in.nextLong(), t = in.nextLong(); if (t < s) { out.println(-1); return; } long[] c = new long[n], v = new long[n]; for (int i = 0; i < n; i++) { c[i] = in.nextLong(); v[i] = in.nextLong(); } ArrayList<Long> g = new ArrayList<>(k + 2); g.add((long) 0); for (int i = 0; i < k; i++) g.add(in.nextLong()); g.add(s); sort(g); k++; for (int i = 0; i < k; i++) g.set(i, g.get(i + 1) - g.get(i)); g.remove(k); sort(g, reverseOrder()); int i = 0; long sum = 0, x = min(t - s, s); for (; i < k && sum < x + g.get(i) * i; i++) sum += g.get(i); long ans = -1; long V = (i > 0 ? (sum - x + i - 1) / i : g.get(0)) + g.get(0); for (int j = 0; j < n; j++) if (v[j] >= V) ans = ans == -1 ? c[j] : min(ans, c[j]); out.println(ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // in = new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
aab209770736b85077c89f8f3353ddc4
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
/* ⣿⣿⣿⣿⣿⣿⡷⣯⢿⣿⣷⣻⢯⣿⡽⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠸⣿⣿⣆⠹⣿⣿⢾⣟⣯⣿⣿⣿⣿⣿⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣻⣽⡿⣿⣎⠙⣿⣞⣷⡌⢻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⡄⠹⣿⣿⡆⠻⣿⣟⣯⡿⣽⡿⣿⣿⣿⣿⣽⡷⣯⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣟⣷⣿⣿⣿⡀⠹⣟⣾⣟⣆⠹⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⡘⣿⣿⡄⠉⢿⣿⣽⡷⣿⣻⣿⣿⣿⣿⡝⣷⣯⢿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣯⢿⣾⢿⣿⡄⢄⠘⢿⣞⡿⣧⡈⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⣧⠘⣿⣷⠈⣦⠙⢿⣽⣷⣻⣽⣿⣿⣿⣿⣌⢿⣯⢿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣟⣯⣿⢿⣿⡆⢸⡷⡈⢻⡽⣷⡷⡄⠻⣽⣿⣿⡿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣏⢰⣯⢷⠈⣿⡆⢹⢷⡌⠻⡾⢋⣱⣯⣿⣿⣿⣿⡆⢻⡿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⡎⣿⢾⡿⣿⡆⢸⣽⢻⣄⠹⣷⣟⣿⣄⠹⣟⣿⣿⣟⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⢸⣯⣟⣧⠘⣷⠈⡯⠛⢀⡐⢾⣟⣷⣻⣿⣿⣿⡿⡌⢿⣻⣿⣿ ⣿⣿⣿⣿⣿⣿⣧⢸⡿⣟⣿⡇⢸⣯⣟⣮⢧⡈⢿⣞⡿⣦⠘⠏⣹⣿⣽⢿⣿⣿⣿⣿⣯⣿⣿⣿⡇⢸⣿⣿⣾⡆⠹⢀⣠⣾⣟⣷⡈⢿⣞⣯⢿⣿⣿⣿⢷⠘⣯⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⡈⣿⢿⣽⡇⠘⠛⠛⠛⠓⠓⠈⠛⠛⠟⠇⢀⢿⣻⣿⣯⢿⣿⣿⣿⣷⢿⣿⣿⠁⣾⣿⣿⣿⣧⡄⠇⣹⣿⣾⣯⣿⡄⠻⣽⣯⢿⣻⣿⣿⡇⢹⣾⣿ ⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⡽⡇⢸⣿⣿⣿⣿⣿⣞⣆⠰⣶⣶⡄⢀⢻⡿⣯⣿⡽⣿⣿⣿⢯⣟⡿⢀⣿⣿⣿⣿⣿⣧⠐⣸⣿⣿⣷⣿⣿⣆⠹⣯⣿⣻⣿⣿⣿⢀⣿⢿ ⣿⣿⣿⣿⣿⣿⣿⣿⠘⣯⡿⡇⢸⣿⣿⣿⣿⣿⣿⣿⣧⡈⢿⣳⠘⡄⠻⣿⢾⣽⣟⡿⣿⢯⣿⡇⢸⣿⣿⣿⣿⣿⣿⡀⢾⣿⣿⣿⣿⣿⣿⣆⠹⣾⣷⣻⣿⡿⡇⢸⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠻⡇⢹⣆⠹⣟⣾⣽⣻⣟⣿⣽⠁⣾⣿⣿⣿⣿⣿⣿⣇⣿⣿⠿⠛⠛⠉⠙⠋⢀⠁⢘⣯⣿⣿⣧⠘⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⣿⡃⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡙⠌⣿⣆⠘⣿⣞⡿⣞⡿⡞⢠⣿⣿⣿⣿⣿⡿⠛⠉⠁⢀⣀⣠⣤⣤⣶⣶⣶⡆⢻⣽⣞⡿⣷⠈⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠘⠁⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⢿⣄⢻⣿⣧⠘⢯⣟⡿⣽⠁⣾⣿⣿⣿⣿⣿⡃⢀⢀⠘⠛⠿⢿⣻⣟⣯⣽⣻⣵⡀⢿⣯⣟⣿⢀⣿ ⣿⣿⣿⣟⣿⣿⣿⣿⣶⣶⡆⢀⣿⣾⣿⣾⣷⣿⣶⠿⠚⠉⢀⢀⣤⣿⣷⣿⣿⣷⡈⢿⣻⢃⣼⣿⣿⣿⣿⣻⣿⣿⣿⡶⣦⣤⣄⣀⡀⠉⠛⠛⠷⣯⣳⠈⣾⡽⣾⢀⣿ ⣿⢿⣿⣿⣻⣿⣿⣿⣿⣿⡿⠐⣿⣿⣿⣿⠿⠋⠁⢀⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣌⣥⣾⡿⣿⣿⣷⣿⣿⢿⣷⣿⣿⣟⣾⣽⣳⢯⣟⣶⣦⣤⡾⣟⣦⠘⣿⢾⡁⢺ ⣿⣻⣿⣿⡷⣿⣿⣿⣿⣿⡗⣦⠸⡿⠋⠁⢀⢀⣠⣴⢿⣿⣽⣻⢽⣾⣟⣷⣿⣟⣿⣿⣿⣳⠿⣵⣧⣼⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣽⣳⣯⣿⣿⣿⣽⢀⢷⣻⠄⠘ ⣿⢷⣻⣿⣿⣷⣻⣿⣿⣿⡷⠛⣁⢀⣀⣤⣶⣿⣛⡿⣿⣮⣽⡻⣿⣮⣽⣻⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢀⢸⣿⢀⡆ ⠸⣟⣯⣿⣿⣷⢿⣽⣿⣿⣷⣿⣷⣆⠹⣿⣶⣯⠿⣿⣶⣟⣻⢿⣷⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢀⣯⣟⢀⡇ ⣇⠹⣟⣾⣻⣿⣿⢾⡽⣿⣿⣿⣿⣿⣆⢹⣶⣿⣻⣷⣯⣟⣿⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢀⡿⡇⢸⡇ ⣿⣆⠹⣷⡻⣽⣿⣯⢿⣽⣻⣿⣿⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⠇⣼⡇ ⡙⠾⣆⠹⣿⣦⠛⣿⢯⣷⢿⡽⣿⣿⣿⣿⣆⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⢀⣿⣾⣣⡿⡇ ⣿⣷⡌⢦⠙⣿⣿⣌⠻⣽⢯⣿⣽⣻⣿⣿⣿⣧⠩⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢰⢣⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⢀⢀⢿⣞⣷⢿⡇ ⣿⣽⣆⠹⣧⠘⣿⣿⡷⣌⠙⢷⣯⡷⣟⣿⣿⣿⣷⡀⡹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣈⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢀⣴⡧⢀⠸⣿⡽⣿⢀ ⢻⣽⣿⡄⢻⣷⡈⢿⣿⣿⢧⢀⠙⢿⣻⡾⣽⣻⣿⣿⣄⠌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢁⣰⣾⣟⡿⢀⡄⢿⣟⣿⢀ ⡄⢿⣿⣷⢀⠹⣟⣆⠻⣿⣿⣆⢀⣀⠉⠻⣿⡽⣯⣿⣿⣷⣈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⢀⣠⠘⣯⣷⣿⡟⢀⢆⠸⣿⡟⢸ ⣷⡈⢿⣿⣇⢱⡘⢿⣷⣬⣙⠿⣧⠘⣆⢀⠈⠻⣷⣟⣾⢿⣿⣆⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⣠⡞⢡⣿⢀⣿⣿⣿⠇⡄⢸⡄⢻⡇⣼ ⣿⣷⡈⢿⣿⡆⢣⡀⠙⢾⣟⣿⣿⣷⡈⠂⠘⣦⡈⠿⣯⣿⢾⣿⣆⠙⠻⠿⠿⠿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⢋⣠⣾⡟⢠⣿⣿⢀⣿⣿⡟⢠⣿⢈⣧⠘⢠⣿ ⣿⣿⣿⣄⠻⣿⡄⢳⡄⢆⡙⠾⣽⣿⣿⣆⡀⢹⡷⣄⠙⢿⣿⡾⣿⣆⢀⡀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⣀⣠⣴⡿⣯⠏⣠⣿⣿⡏⢸⣿⡿⢁⣿⣿⢀⣿⠆⢸⣿ ⣿⣿⣿⣿⣦⡙⣿⣆⢻⡌⢿⣶⢤⣉⣙⣿⣷⡀⠙⠽⠷⠄⠹⣿⣟⣿⣆⢙⣋⣤⣤⣤⣄⣀⢀⢀⢀⢀⣾⣿⣟⡷⣯⡿⢃⣼⣿⣿⣿⠇⣼⡟⣡⣿⣿⣿⢀⡿⢠⠈⣿ ⣿⣿⣿⣿⣿⣷⣮⣿⣿⣿⡌⠁⢤⣤⣤⣤⣬⣭⣴⣶⣶⣶⣆⠈⢻⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣷⣶⣤⣌⣉⡘⠛⠻⠶⣿⣿⣿⣿⡟⣰⣫⣴⣿⣿⣿⣿⠄⣷⣿⣿⣿ */ import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws Exception { Reader s=new Reader(); int n=s.nextInt(); int k=s.nextInt(); long d=s.nextLong(); long t=s.nextLong(); long[][] car=new long[n][2]; long max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { car[i][0]=s.nextLong(); car[i][1]=s.nextLong(); max=Math.max(car[i][1], max); } Long[] gas=new Long[k+2]; gas[0]=0l; for(int i=1;i<gas.length-1;i++) { gas[i]=s.nextLong(); } gas[k+1]=d; Arrays.sort(gas); long min=Long.MAX_VALUE; long st=0; long end=max; long ans=-1; while(st<=end) { long mid=(st+end)/2; long time=0; int flag=0; for(int i=0;i<gas.length-1;i++) { long dist=gas[i+1]-gas[i]; long g=0; if(dist>mid) { g=-1; }else { g=Math.min(dist, mid-dist); } if(g==-1) { flag=1; }else { time=time+g+(dist-g)*2; } } if(time>t) { flag=1; } if(flag==1) { st=mid+1; }else { ans=mid; end=mid-1; } } if(ans==-1) { System.out.println(-1); }else { for(int i=0;i<n;i++) { if(car[i][1]>=ans) { min=Math.min(min, car[i][0]); } } System.out.println(min); } } public static long bs(long d,long cap) { long ans=-1; long st=0; long end=d; while(st<=end) { long mid=(st+end)/2; if(mid*2+d-mid<=cap) { ans=mid; st=mid+1; }else { end=mid-1; } } return ans; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
29a4cf150fdd64f1dd991b41590e6939
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.*; import java.util.*; public class SolveC { BufferedReader br; StringTokenizer st; PrintWriter out; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws NumberFormatException, IOException { new SolveC().run(); } void run() throws NumberFormatException, IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } class Segment implements Comparable<Segment>{ long begin; long end; long len; public Segment(long begin, long end) { this.begin = begin; this.end = end; this.len = end - begin; } @Override public int compareTo(Segment that) { if (this.len == that.len) { return Long.compare(this.begin, that.begin); } return Long.compare(this.len, that.len); } } void solve() throws NumberFormatException, IOException { int n = nextInt(); int k = nextInt(); long s = nextInt(); long t = nextInt(); long[] c = new long[n]; long[] v = new long[n]; for (int i = 0; i < n; i++) { c[i] = nextLong(); v[i] = nextLong(); } long[] g = new long[k + 2]; g[0] = 0; g[1] = s; for (int i = 2; i <= k + 1; i++) { g[i] = nextLong(); } Arrays.sort(g); Segment[] segments = new Segment[k + 1]; for (int i = 0; i <= k; i++) { segments[i] = new Segment(g[i], g[i + 1]); } if (s > t) { out.println(-1); return; } Arrays.sort(segments); long vcur = segments[segments.length - 1].len; long tcur = 2 * s; for (Segment seg : segments) { long len = seg.len; long mint = tcur; long minv = vcur; long maxt = tcur - len; long maxv = Math.max(vcur, len * 2); if (maxt > t) { tcur = maxt; vcur = maxv; continue; } else { //[maxt,mint] long res = mint - 2 * len; long a = t - len - res; long b = len - a; tcur = t; vcur = Math.max(vcur, a + 2 * b); break; } } if (tcur != t) { out.println(-1); return; } long ans = Long.MAX_VALUE; for (int i =0; i < n; i++) { if (v[i] >= vcur) { ans = Math.min(ans, c[i]); } } if (ans == Long.MAX_VALUE) { out.println(-1); return; } out.println(ans); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
65227a5fb5fada316ef8d795c44aa31c
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { public static void main(String[] args) { MyScanner in = new MyScanner(); int n = in.nextInt(); int k = in.nextInt(); int s = in.nextInt(); int t = in.nextInt(); int[][] cars = new int[n][2]; for (int i = 0; i < n; ++i) { cars[i][0] = in.nextInt(); cars[i][1] = in.nextInt(); } int[] pos = new int[k]; for (int i = 0; i < k; ++i) { pos[i] = in.nextInt(); } Arrays.sort(pos); long low = 0; long high = 2000_000_010; while (low + 1 < high) { long mid = (low + high) / 2; if (f(pos, mid, t, s)) { high = mid; } else { low = mid; } } int minPrice = Integer.MAX_VALUE; for(int i=0;i<n;++i){ if(cars[i][1]>=high){ minPrice = Math.min(minPrice,cars[i][0]); } } if(minPrice==Integer.MAX_VALUE){ System.out.println(-1); }else{ System.out.println(minPrice); } } private static boolean f(int[] pos, long v, int t, int s) { int currX = 0; int nextStation = 0; int currTime = 0; while(currX<s){ if(nextStation<pos.length && pos[nextStation]<s){ int distance = pos[nextStation] - currX; if(minTime(distance,v)==-1){ return false; } currTime += minTime(distance,v); nextStation++; currX+=distance; }else{ int distance = s - currX; if(minTime(distance,v)==-1){ return false; } currTime += minTime(distance,v); currX+=distance; } } // if(currTime<=t){ // System.out.println(" V "+v); // } return currTime<=t; } private static long minTime(int distance, long v) { if(v<distance){ return -1; } long delta = v-distance; if(delta>=distance){ return distance; } return delta + (distance - delta) * 2; } // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
a4dc5ea63c92a48077e086ced0571ff5
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.util.stream.*; import java.io.*; import java.math.*; public class Main { static boolean FROM_FILE = false; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { if (FROM_FILE) { try { br = new BufferedReader(new FileReader("input.txt")); } catch (IOException error) { } } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int max(int... nums) { int res = Integer.MIN_VALUE; for (int num: nums) res = Math.max(res, num); return res; } static int min(int... nums) { int res = Integer.MAX_VALUE; for (int num: nums) res = Math.min(res, num); return res; } static long max(long... nums) { long res = Long.MIN_VALUE; for (long num: nums) res = Math.max(res, num); return res; } static long min(long... nums) { long res = Long.MAX_VALUE; for (long num: nums) res = Math.min(res, num); return res; } static FastReader fr = new FastReader(); static PrintWriter out; public static void main(String[] args) { if (FROM_FILE) { try { out = new PrintWriter(new FileWriter("output.txt")); } catch (IOException error) { } } else { out = new PrintWriter(new OutputStreamWriter(System.out)); } new Main().run(); out.flush(); out.close(); } int minimumTime(int[] dist, int tank) { int res = 0; for (int d : dist) { if (d > tank) return Integer.MAX_VALUE; if (d * 2 <= tank) res += d; else { double rate = 1 - (1.0 * tank / d - 1); int t = (int)Math.ceil(d * (1 + rate)); res += t; } } return res; } void run() { int n = fr.nextInt(), k = fr.nextInt(), s = fr.nextInt(), t = fr.nextInt(); if (s > t) { out.println(-1); return; } int[][] cars = new int[n][2]; for (int i = 0; i < n; i += 1){ cars[i][0] = fr.nextInt(); cars[i][1] = fr.nextInt(); } int[] gas = new int[k + 1]; for (int i = 1; i <= k; i += 1) { gas[i] = fr.nextInt(); } Arrays.sort(gas); int[] dist = new int[k + 1]; for (int i = 0; i < k; i += 1) { dist[i] = gas[i + 1] - gas[i]; } dist[k] = s - gas[k]; // out.println(Arrays.toString(dist)); // out.println(minimumTime(dist, 8) + " " + t); // binary search on tank size int lo = 1, hi = max(dist) * 2; while (lo < hi) { int mid = lo + (hi - lo) / 2; int time = minimumTime(dist, mid); if (time > t) lo = mid + 1; else hi = mid; } int res = -1; for (int i = 0; i < n; i += 1) { if (cars[i][1] >= lo) { if (res == -1 || res > cars[i][0]) res = cars[i][0]; } } out.println(res); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
5762460e27e5e9bc1b816424f80df06b
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class lp{ static PrintWriter out = new PrintWriter(System.out); static long max = 10000000000000l; static boolean ok(long mid,long s,long t,int g[]) { int prev=0; long tt=0; for(int i=0;i<g.length;i++) { long d =g[i]-prev; if(d>mid) return false; long fast_mode = Math.min(d,mid-d); long slow_mode = d-fast_mode; tt = tt + fast_mode + slow_mode*2; prev = g[i]; } long d =s-prev; if(d>mid) return false; long fast_mode = Math.min(d,mid-d); long slow_mode = d-fast_mode; tt = tt + fast_mode + slow_mode*2; if(tt<=t) return true; return false; } static void solve() throws Exception{ int n = ni(); int k = ni(); long s = nl(); long t = nl(); int c[] = new int[n]; int v[] = new int[n]; for(int i=0;i<n;i++) { c[i] = ni(); v[i] = ni(); } int g[] = ai(k); Arrays.sort(g); long l=0,r=max; while((r-l)>1) { long mid = (l+r)/2; if(ok(mid,s,t,g)) r=mid; else l=mid; } long price= max; for(int i=0;i<n;i++) if(v[i]>=r) price = Math.min(price,c[i]); if(price==max) price=-1; pn(price); out.flush(); } public static void main(String[] args){ // use this block when you need more recursion depth new Thread(null, null, "Name", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int[] ai(int n) // it will give in array of size n { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = ni(); return a; } static long[] al(int n) // it will give in array of size n { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nl(); return a; } static void p(Object o) { out.print(o); } static void pn(Object o) { out.println(o); } static int abs(int x) { return x>0 ? x : -x; } static long gcd(long a,long b) { if(b%a==0) return a; return gcd(b%a,a); } static int count_set(int n) { int c=0; while(n>0) { if(n%2==1) c++; n=n/2; } return c; } static void subtract_1(char s[]) // it will subtract 1 from the given number. number should be positive { if(s[0]=='0') // number is zero return; int n = s.length,i=n-1; while(s[i]=='0') i--; s[i] = (char)((int)(s[i]-'0') + 47); for(int j=i+1;j<n;j++) s[j]='9'; } static long pow(long a,long b,long md) { long ans=1; while(b>0) { if(b%2==1) ans = (ans*a)%md; a = (a*a)%md; b = b/2; } return ans; } static long min(long a,long b){ return a<b ? a : b; } static long max(long a,long b){ return a>b ? a : b; } static boolean pal(String s) { int n = s.length(),i1=0,i2=n-1; while(i1<i2) { if(s.charAt(i1)!=s.charAt(i2)) return false; i1++; i2--; } return true; } static String rev(String r) { String s = ""; int i= r.length()-1; while(i>=0) { s=s+r.charAt(i); i--; } return s; } 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
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
89d184253cb1fc211a9e3a37b623118a
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.FileNotFoundException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class Main{ public static void main(String[] args) throws FileNotFoundException { Scanner scanner =new Scanner(System.in); // Scanner scanner =new Scanner(new FileInputStream("src/in.txt")); int n=scanner.nextInt(); int k=scanner.nextInt(); int s=scanner.nextInt(); int t=scanner.nextInt(); int [] c=new int[n]; int [] v=new int[n]; for(int i=0;i<n;i++){ c[i]=scanner.nextInt(); v[i]=scanner.nextInt(); } int pre = 0; int []g=new int[k]; for(int i=0;i<k;i++){ g[i]=scanner.nextInt(); } Arrays.sort(g); List<Integer> list = new LinkedList<>(); for(int i=0;i<k;i++){ int cnt = g[i]; list.add(cnt-pre); pre=cnt; } list.add(s-pre); int l=0,r=Integer.MAX_VALUE/2; int ans = Integer.MAX_VALUE; while (r>=l){ int mid=(l+r)>>1; int cost = 0; for(int p:list){ if(p>mid){ cost=Integer.MAX_VALUE; break; } if(p*2<=mid){ cost+=p; }else{ cost+=3*p-mid; } } if(cost>t){ l=mid+1; }else{ ans=mid; r=mid-1; } // System.out.println(mid+" "+cost); } int ret = Integer.MAX_VALUE; for(int i=0;i<n;i++){ if(ans<=v[i]){ ret=Math.min(ret,c[i]); } } if(ret==Integer.MAX_VALUE){ ret=-1; } System.out.println(ret); } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
b0a9ca879b64af311495fe0d2edc99a5
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class elmovies { public static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); public static StringTokenizer st; public static PrintWriter pw = new PrintWriter(System.out); final static boolean debugmode = true; public static int k = 7; // for 10^9 + k mods. public static long STMOD = 1000000000 + k; // 10^9 + k public static void main(String[] args) throws IOException{ int ncars = getInt(); int stations = getInt(); int epoint = getInt(); int timeCut = getInt(); int[][] cars = new int[ncars][2]; for(int i = 0;i<ncars;i++){ cars[i][1] = getInt(); cars[i][0] = getInt(); } int[] restpoints = new int[stations+2]; for(int i = 0;i<stations;i++){ restpoints[i+1] = getInt(); } restpoints[stations+1] = epoint; restpoints[0] = 0; Arrays.sort(restpoints); Arrays.sort(cars, new java.util.Comparator<int[]>(){ @Override public int compare(int[] arg0, int[] arg1) { // TODO Auto-generated method stub return arg0[0]-arg1[0]; }}); if(!testcar(cars[cars.length-1][0], restpoints, timeCut)){ submit(-1,true); return; } int hi = cars.length-1; int lo = -1; while(Math.abs(hi-lo) > 1){ int mid = hi + lo; mid /= 2; if(testcar(cars[mid][0], restpoints, timeCut)){ //System.out.println(Arrays.toString(cars[mid])+" worked!"); hi = mid; } else{ //System.out.println(Arrays.toString(cars[mid])+" failed.!"); lo = mid; } } int ccost = cars[hi][1]; for(int i = hi;i<cars.length;i++){ ccost = Math.min(ccost, cars[i][1]); } submit(ccost,true); } public static boolean testcar(double mxf,int[] rp,double limit){ //System.out.println(Arrays.toString(rp)); double ttime = 0; for(int dest = 1;dest < rp.length;dest++){ double v = time(rp[dest]-rp[dest-1],mxf); if(v == -1){ return false; // unreachable. } ttime += v; if(ttime > limit){ return false; } } //System.out.println("Made with: "+mxf+" in "+ttime); return true; } public static double time(double distance, double fuels){ if(distance <= fuels/2){ return distance; } else if(distance > fuels){ return -1; } double k = 2*distance - fuels; return distance + k; } public static void setInputFile(String fn) throws IOException{ sc = new BufferedReader(new FileReader(fn)); } public static void setOutputFile(String fn) throws IOException{ pw = new PrintWriter(new BufferedWriter(new FileWriter(fn))); } public static int GCD(int a, int b) { if (b==0) return a; return GCD(b,a%b); } public static double log(int k, int v){ return Math.log(k)/Math.log(v); } public static long longpower(int a,int b){ long[] vals = new long[(int) (log(b,2)+2)]; vals[0] = a; vals[1] = a*a; for(int i = 1;i<vals.length;i++){ vals[i] = vals[i-1]*vals[i-1]; } long ans = 1; int cindex = 0; while(b != 0){ if (b % 2 == 1){ ans *= vals[cindex]; } cindex += 1; b /= 2; } return ans; } public static void debug(String toPrint){ if(!debugmode) {return;} pw.println("[DEBUG]: "+toPrint); } public static void submit(int[] k,boolean close){ pw.println(Arrays.toString(k)); if(close){ pw.close(); } } public static void submit(int p,boolean close){ pw.println(Integer.toString(p)); if(close){ pw.close(); } } public static void submit(String k,boolean close){ pw.println(k); if(close){ pw.close(); } } public static void submit(double u,boolean close){ pw.println(Double.toString(u)); if(close){ pw.close(); } } public static void submit(long lng,boolean close){ pw.println(Long.toString(lng)); if(close){ pw.close(); } } public static void submit(){ pw.close(); } public static int getInt() throws IOException{ if (st != null && st.hasMoreTokens()){ return Integer.parseInt(st.nextToken()); } st = new StringTokenizer(sc.readLine()); return Integer.parseInt(st.nextToken()); } public static long getLong() throws IOException{ if (st != null && st.hasMoreTokens()){ return Long.parseLong(st.nextToken()); } st = new StringTokenizer(sc.readLine()); return Long.parseLong(st.nextToken()); } public static double getDouble()throws IOException{ if (st != null && st.hasMoreTokens()){ return Double.parseDouble(st.nextToken()); } st = new StringTokenizer(sc.readLine()); return Double.parseDouble(st.nextToken()); } public static String getString()throws IOException{ if(st != null && st.hasMoreTokens()){ return st.nextToken(); } st = new StringTokenizer(sc.readLine()); return st.nextToken(); } public static String getLine() throws IOException{ return sc.readLine(); } public static int[][] readMatrix(int lines,int cols) throws IOException{ int[][] matrr = new int[lines][cols]; for (int i = 0;i < lines;i++){ for(int j = 0;j < cols;j++){ matrr[i][j] = getInt(); } } return matrr; } public static int[] readArray(int lines) throws IOException{ int[] ar = new int[lines]; for (int i = 0;i<lines;i++) ar[i] =getInt(); return ar; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
6109bd4d77f72feee0d37d7f2e0156ca
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
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.StringTokenizer; public class Road_To_Cinema_CD729C { static carro lista[]; static int s; static int t; static int paradas[]; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String linea = in.readLine(); while(linea!=null&&!linea.trim().equals("")){ StringTokenizer toks = new StringTokenizer (linea); int n = Integer.parseInt(toks.nextToken()); int k =Integer.parseInt(toks.nextToken()); s = Integer.parseInt(toks.nextToken()); t =Integer.parseInt(toks.nextToken()); lista = new carro[n]; paradas = new int [k+1]; for (int i = 0; i < n; i++) { toks= new StringTokenizer(in.readLine()); lista[i]= new carro(Integer.parseInt(toks.nextToken()),Integer.parseInt(toks.nextToken())); } toks=new StringTokenizer(in.readLine()); for (int i = 0; i < k; i++) { paradas[i]=Integer.parseInt(toks.nextToken()); } paradas[k]=s; Arrays.sort(paradas); Arrays.sort(lista); long res =solve(); if(res==Integer.MAX_VALUE) out.println(-1); else{ boolean puede=false; for (int i = 0; i < lista.length; i++) { if(lista[i].tanque>=res){ out.println(lista[i].precio); i=lista.length; puede =true; } } if(puede==false) out.println(-1); } linea =in.readLine(); } out.close(); } static long solve (){ long a =0; long b=s*2; long mejor=Integer.MAX_VALUE; long m=0; while(a<=b){ m=(a+b)/2; if(puede(m)){ mejor=Math.min(m, mejor); b=m-1; }else{ a=m+1; } } return mejor; } static boolean puede(long m){ long tiempo =0; long pos=0; long dis=0; for (int i = 0; i < paradas.length; i++) { dis=paradas[i]-pos; if(m/2>=dis){ tiempo+=dis; }else if((m/2)+m%2>=dis){ tiempo+=(m/2)+(m%2)*2; }else if(dis==m){ tiempo+=m*2; }else if(m>dis){ long temp=m-dis; tiempo+=temp+(dis-temp)*2; } else return false; pos=paradas[i]; } if(tiempo<=t) return true; else return false; } } class carro implements Comparable<carro>{ int precio; int tanque; @Override public int compareTo(carro o) { return Integer.compare(this.precio, o.precio); } carro(int precio,int tanque){ this.precio=precio; this.tanque=tanque; } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
58bd2d6852a0debf38f0c52303505c1b
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class codeforces729C { public static boolean checkIfPossible(int[] distance,int k,int t,int fuel) { int time = 0; for(int i=0;i<=k;i++) { if(distance[i]>fuel) { return false; } else if(fuel>=2*distance[i]){ time+=distance[i]; } else { time+=(3*distance[i]-fuel); } } return time<=t; } public static int findingMinimumTime(int left,int right,int k,int t,int[] distance) { while(left+1<right) { int mid = (left+right)/2; if(checkIfPossible(distance,k,t,mid)) { right = mid; } else { left = mid; } } return right; } public static void main(String[] args) throws Exception{ //InputReader in = new InputReader(new File("C:/Users/RED-DRAGON/workspace/input.txt")); InputReader in = new InputReader(System.in); //PrintWriter out = new PrintWriter(new File("C:/Users/RED-DRAGON/workspace/output.txt")); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); int k = in.nextInt(); int s = in.nextInt(); int t = in.nextInt(); int[] c = new int[n+1]; int[] v = new int[n+1]; int vmax = Integer.MIN_VALUE; for(int i=0;i<n;i++) { c[i] = in.nextInt(); v[i] = in.nextInt(); vmax = Math.max(vmax, v[i]); } int[] g = new int[k]; for(int i=0;i<k;i++) { g[i] = in.nextInt(); } Arrays.sort(g); int[] distance = new int[k+1]; distance[0] = g[0]; for(int i=1;i<k;i++) { distance[i] = g[i] - g[i-1]; } distance[k] = s-g[k-1]; //out.println(checkIfPossible(distance,k,t,vmax)); if(!checkIfPossible(distance,k,t,vmax)) { out.println(-1); } else { int minimumTime = findingMinimumTime(0,vmax,k,t,distance); int rslt = Integer.MAX_VALUE; for(int i=0;i<n;i++) { if(v[i]>=minimumTime) { rslt = Math.min(rslt, c[i]); } } out.println(rslt); } out.close(); } public static void debug(Object...args) { System.out.println(Arrays.deepToString(args)); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(File file) { try { reader = new BufferedReader(new FileReader(file)); tokenizer = null; } catch(FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() throws Exception { while(tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public String nextLine() throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt() throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
dc96f172c442ac523b8bf08782344471
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.io.*; public class codeforces729C { public static boolean checkIfPossible(int[] distance,int k,int t,int fuel) { int time = 0; for(int i=0;i<=k;i++) { if(distance[i]>fuel) { return false; } else if(fuel>=2*distance[i]){ time+=distance[i]; } else { time+=(3*distance[i]-fuel); } } return time<=t; } public static int findingMinimumTime(int left,int right,int k,int t,int[] distance) { while(left<right) { int mid = (left+right)/2; if(checkIfPossible(distance,k,t,mid)) { right = mid; } else { left = mid+1; } } return right; } public static void main(String[] args) throws Exception{ //InputReader in = new InputReader(new File("C:/Users/RED-DRAGON/workspace/input.txt")); InputReader in = new InputReader(System.in); //PrintWriter out = new PrintWriter(new File("C:/Users/RED-DRAGON/workspace/output.txt")); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); int k = in.nextInt(); int s = in.nextInt(); int t = in.nextInt(); int[] c = new int[n+1]; int[] v = new int[n+1]; int vmax = Integer.MIN_VALUE; for(int i=0;i<n;i++) { c[i] = in.nextInt(); v[i] = in.nextInt(); vmax = Math.max(vmax, v[i]); } int[] g = new int[k]; for(int i=0;i<k;i++) { g[i] = in.nextInt(); } Arrays.sort(g); int[] distance = new int[k+1]; distance[0] = g[0]; for(int i=1;i<k;i++) { distance[i] = g[i] - g[i-1]; } distance[k] = s-g[k-1]; //out.println(checkIfPossible(distance,k,t,vmax)); if(!checkIfPossible(distance,k,t,vmax)) { out.println(-1); } else { int minimumTime = findingMinimumTime(1,vmax,k,t,distance); int rslt = Integer.MAX_VALUE; for(int i=0;i<n;i++) { if(v[i]>=minimumTime) { rslt = Math.min(rslt, c[i]); } } out.println(rslt); } out.close(); } public static void debug(Object...args) { System.out.println(Arrays.deepToString(args)); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(File file) { try { reader = new BufferedReader(new FileReader(file)); tokenizer = null; } catch(FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() throws Exception { while(tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public String nextLine() throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt() throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
946d372a95b49cc4311a065bcc7b8bfb
train_000.jsonl
1479632700
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.*; public class A { static class Node implements Comparable<Node>{ long price; long cap; public Node(long price, long cap){ this.price=price; this.cap=cap; } public int compareTo(Node c){ return Long.compare(this.cap,c.cap); } @Override public boolean equals(Object o){ if(o instanceof Node){ Node c = (Node)o; } return false; } } //public static PrintWriter pw; public static PrintWriter pw = new PrintWriter(System.out); public static void solve() throws IOException { // pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in")); FastReader sc = new FastReader(); int n =sc.I(); int k=sc.I(); long s=sc.L(); long t=sc.L(); Node p[]=new Node[n]; for(int i=0;i<n;i++){ long price=sc.L(); long cap=sc.L(); p[i]=new Node(price,cap); } gas=new long[k]; for(int i=0;i<k;i++) gas[i]=sc.L(); Arrays.sort(gas); long ans=Long.MAX_VALUE; long l=0,h=(long)1e9; while(l<=h){ long cap=(l+h)/2; if(can(cap,k,s,t)){ for(int i=0;i<n;i++){ if(p[i].cap>=cap) ans=Math.min(ans,p[i].price); } h=cap-1; }else l=cap+1; } if(ans==Long.MAX_VALUE) pw.println(-1); else pw.println(ans); pw.close(); } static long gas[]; static boolean can(long cap,int k,long s,long time){ long prev=0; long tme=0; for(int i=0;i<k;i++){ long d=gas[i]-prev; if(cap<d)return false; long dfast=Math.min(d,cap-d); tme+=dfast+2*(d-dfast); prev=gas[i]; } long d=s-prev; if(cap<d)return false; long dfast=Math.min(d,cap-d); tme+=dfast+2*(d-dfast); if(tme>time) return false; return true; } 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 BufferedReader br; static long M = (long) 1e9 + 7; static class FastReader { StringTokenizer st; public FastReader() throws FileNotFoundException { //br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in")); 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 I() { return Integer.parseInt(next()); } long L() { return Long.parseLong(next()); } double D() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public boolean hasNext() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } return true; } } }
Java
["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"]
1 second
["10", "20"]
NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Java 8
standard input
[ "binary search", "sortings", "greedy" ]
740a1ee41a5a4c55b505abb277c06b8a
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
1,700
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
standard output
PASSED
4a1994383c5803d025234c258e1a4815
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; public class MainClass { static boolean ff = false; public static void main(String[] args)throws IOException { Reader in = new Reader(); StringBuilder stringBuilder = new StringBuilder(); int t = in.nextInt(); while (t-- > 0) { ff = false; int n = in.nextInt(); ArrayList<Integer>[] adj = new ArrayList[n]; for (int i=0;i<n;i++) adj[i] = new ArrayList<>(); for (int i=0;i<n;i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; adj[x].add(y); adj[y].add(x); } Stack<Integer> onStack = new Stack<>(); boolean[] visited = new boolean[n]; boolean[] onCycle = new boolean[n]; dfs(adj, 0, visited, onStack, onCycle, -1); Arrays.fill(visited, false); for (int i=0;i<n;i++) { if (onCycle[i]) { visited[i] = true; } } ArrayList<Integer> B = new ArrayList<>(); for (int i=0;i<n;i++) { if (onCycle[i]) { int xx = explore(adj, i, visited); B.add(xx); } } long ans = 1L * n * (n - 1L); for (long xxx : B) { ans -= (xxx * (xxx - 1L)) / 2L; } stringBuilder.append(ans).append("\n"); } System.out.println(stringBuilder); } public static int explore(ArrayList<Integer>[] adj, int v, boolean[] vis) { vis[v] = true; int ans = 1; for (int u : adj[v]) { if (!vis[u]) { ans += explore(adj, u, vis); } } return ans; } public static void dfs(ArrayList<Integer>[] adj, int v, boolean[] vis, Stack<Integer> onStack, boolean[] onCycle, int par) { if (ff) return; vis[v] = true; onStack.push(v); for (int u : adj[v]) { if (ff) return; if (!vis[u]) { dfs(adj, u, vis, onStack, onCycle, v); } else if (u != par) { ff = true; onCycle[u] = true; while (onStack.peek() != u) { onCycle[onStack.pop()] = true; } return; } } if (ff) return; onStack.pop(); } } 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(); } } /* 1, 2 1, 2, 3 1, 4 1, 3, 2 1, 5 1, 3 [1, ..., 4] [1, ..., 5] 2, 3 2, 1, 3 2, 1, 4 2, 1, 5 2, 3, 1, 4 2, 3, 1, 5 3, 1, 4 3, 1, 5 3, 2, 1, 4 3, 2, 1, 5 4, 1, 5 [4, ..., 5] */
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
7ba7f187ffe6e19b2e88934e448c45cb
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; public class CodeforcesContest { private static long sport(List<Integer>[] graph, int n) { CycleFinder cycleFinder = new CycleFinder(graph, n); List<Integer> cycle = cycleFinder.findCycle(); Set<Integer> set = new HashSet<>(cycle); long ans = 0; for (Integer i : cycle) { long cnt = 1 + dfs(graph, new HashSet<>(), i, set); // System.out.println("-- " + cnt); ans += cnt * (cnt - 1) / 2 + cnt * (n - cnt); } return ans; } // 2 2 1 //14+4 private static long dfs(List<Integer>[] graph, Set<Integer> seen, int v, Set<Integer> cycle) { long ans = 0; seen.add(v); for (Integer i : graph[v]) { if (!seen.contains(i) && !cycle.contains(i)) { ans += 1 + dfs(graph, seen, i, cycle); } } return ans; } private static class CycleFinder { List<Integer>[] graph; int n; boolean[] marked; boolean[] onStack; int[] parent; List<Integer> cycle = new ArrayList<>(); public CycleFinder(List<Integer>[] graph, int n) { this.graph = graph; this.n = n; this.marked = new boolean[n + 1]; this.onStack = new boolean[n + 1]; this.parent = new int[n + 1]; dfs(1, -1); } private void dfs(int v, int from) { marked[v] = true; onStack[v] = true; for (Integer i : graph[v]) { if (i == from) { continue; } if (!marked[i]) { parent[i] = v; dfs(i, v); } else if (onStack[i]) { int x = parent[v]; while (x != i) { cycle.add(x); x = parent[x]; } cycle.add(i); cycle.add(v); } } onStack[v] = false; } public List<Integer> findCycle() { return cycle; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int exp = sc.nextInt(); for (int i = 0; i < exp; i++) { int n = sc.nextInt(); List<Integer>[] graph = new ArrayList[n + 1]; for (int j = 0; j <= n; j++) { graph[j] = new ArrayList<>(); } for (int j = 0; j < n; j++) { int from = sc.nextInt(); int to = sc.nextInt(); graph[from].add(to); graph[to].add(from); } System.out.println(sport(graph, n)); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
79e2d708829441e5b206664a66d9d948
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.*; import java.util.*; public class A { static BufferedReader br; static int cin() throws Exception { return Integer.valueOf(br.readLine()); } static int[] split() throws Exception { String[] cmd=br.readLine().split(" "); int[] ans=new int[cmd.length]; for(int i=0;i<cmd.length;i++) { ans[i]=Integer.valueOf(cmd[i]); } return ans; } static long[] splitL() throws IOException { String[] cmd=br.readLine().split(" "); long[] ans=new long[cmd.length]; for(int i=0;i<cmd.length;i++) { ans[i]=Long.valueOf(cmd[i]); } return ans; } static ArrayList<Integer>[]gr; static int[]vis; static int dfs(int node) { if(vis[node]==1 || check[node]==1) return 0; vis[node]=1; int size=1; for(int i=0;i<gr[node].size();i++) { size+=dfs(gr[node].get(i)); } return size; } static int[]check; public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub br=new BufferedReader(new InputStreamReader(System.in)); int cases=cin(); while(cases!=0) { cases--; int n=cin(); gr=new ArrayList[n+1]; for(int i=0;i<=n;i++) { gr[i]=new ArrayList<>(); } int[]deg=new int[n+1]; for(int i=0;i<n;i++) { int[]ar=split(); int x=ar[0]; int y=ar[1]; gr[x].add(y); gr[y].add(x); deg[x]++; deg[y]++; } vis=new int[n+1]; Queue<Integer>q=new LinkedList<>(); int[]mark=new int[n+1]; for(int i=1;i<=n;i++) { if(deg[i]==1) { mark[i]=1; q.add(i); } } int[]val=new int[n+1]; Arrays.fill(val,1); while(!q.isEmpty()) { int node=q.poll(); for(int i=0;i<gr[node].size();i++) { int y=gr[node].get(i); if(mark[y]==1) continue; val[y]+=val[node]; deg[y]--; if(deg[y]<=1) { q.add(y); mark[y]=1; } } } ArrayList<Integer>cycle=new ArrayList<>(); check=new int[n+1]; for(int i=1;i<=n;i++) { if(mark[i]==0) { check[i]=1; cycle.add(i); } } //System.out.println(cycle); long ans=(long)((long)n*(n-1)); for(int i=0;i<cycle.size();i++) { // int x=cycle.get(i); // vis=new int[n+1]; // check[x]=0; // int y=dfs(x); // check[x]=1; //System.out.println(x+" "+y); int x=cycle.get(i); ans=ans-(long)((long)val[x]*(val[x]-1))/2; } System.out.println(ans); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
b465d4395f083a3e0c2fc647a952c316
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; public class Ana { static int n, p[]; static boolean vis[], inCycle[], found; static ArrayList<Integer>[] graph; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int tt = sc.nextInt(); while (tt-- > 0) { n = sc.nextInt(); graph = new ArrayList[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1; graph[u].add(v); graph[v].add(u); } vis = new boolean[n]; inCycle = new boolean[n]; p = new int[n]; p[0] = -1; found = false; dfs(0); // Queue<Integer> q= new LinkedList<Integer>(); // vis[0] = true; // q.add(0); // bfs:while(!q.isEmpty()) { // int u=q.remove(); // System.out.println(u); // for(int v:graph[u]) // if(v!=p[u]) { // if(vis[v]) { // System.out.println(u+" "+v); // p[v] = u; // while(u!=v) { // inCycle[u] = true; // u = p[u]; // } // inCycle[v] = true; // break bfs; // } // q.add(v); // vis[v] = true; // } // // } // System.out.println(Arrays.toString(inCycle)); long ans = 0; for (int i = 0; i < n; i++) if (inCycle[i]) { int cnt = dfs2(i, -1); ans += 1l * cnt * (n - cnt); } ans/=2; ans+=1l*n*(n-1)/2; out.println(ans); } out.close(); } private static int dfs2(int u, int p) { int cnt = 1; for (int v : graph[u]) if (v != p && !inCycle[v]) cnt += dfs2(v, u); return cnt; } static void dfs(int u) { if (vis[u] || found) return; vis[u] = true; for (int v : graph[u]) { if(found) return; if (v != p[u]) { p[v] = u; if (vis[v]) { // System.out.println(u + " " + v); while (u != v) { inCycle[u] = true; u = p[u]; } inCycle[v] = true; found = true; return; } dfs(v); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(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 int[] nextIntArray(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } 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\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
7372749b56d286203532a5641e1dd8e2
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; public class StringTask { private final static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { FastScanner fastScanner = new FastScanner(); int t = fastScanner.nextInt(); for (int i = 0; i < t; i++) { int n = fastScanner.nextInt(); List<Set<Integer>> graph = new ArrayList<>(); for (int j = 0; j < n; j++) { graph.add(new HashSet<>()); } for (int j = 1; j <= n; j++) { int s = fastScanner.nextInt(); int d = fastScanner.nextInt(); graph.get(s - 1).add(d - 1); graph.get(d - 1).add(s - 1); } runTest(graph); } } private static void runTest(List<Set<Integer>> graph) { int n = graph.size(); List<Integer> values = IntStream.range(0, n).map(i -> 1).boxed().collect(Collectors.toList()); Queue<Integer> leafs = new ArrayDeque<>(); for (int i = 0; i < n; i++) { if (graph.get(i).size() == 1) { leafs.add(i); } } while (!leafs.isEmpty()) { int v = leafs.remove(); int to = graph.get(v).stream().findFirst().get(); values.set(to, values.get(to) + values.get(v)); values.set(v, 0); graph.get(v).clear(); graph.get(to).remove(v); if (graph.get(to).size() == 1) { leafs.add(to); } } long ans = 0; for (int i = 0; i < n; i++) { ans += (long) values.get(i) * (values.get(i) - 1) / 2; ans += (long) values.get(i) * (n - values.get(i)); } System.out.println(ans); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
6dcd3082b198e9f2de9cef6ecb98744b
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.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.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class EX1_8 { static ArrayList<Integer>[] g; static boolean[] vis; static int[] parent; static ArrayList<Integer> cycle; static HashSet<Integer> hs; static boolean dfs(int u, int pa) { vis[u] = true; parent[u] = pa; for (int v : g[u]) { if (v == pa) continue; if (vis[v]) { int x = u; while (x != v) { cycle.add(x); hs.add(x); x = parent[x]; } hs.add(x); cycle.add(x); return true; } if (dfs(v, u)) return true; } return false; } static long ans; static int count(int u, int pa) { int c = 1; for (int v : g[u]) { if (v == pa || hs.contains(v)) continue; c += count(v, u); } return c; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); g = new ArrayList[n]; parent = new int[n]; for (int i = 0; i < g.length; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < g.length; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int u = Integer.parseInt(st.nextToken()) - 1; int v = Integer.parseInt(st.nextToken()) - 1; g[u].add(v); g[v].add(u); } vis = new boolean[n]; cycle = new ArrayList<>(); hs = new HashSet<>(); dfs(0, -1); long ans = 0; // System.out.println(cycle); HashMap<Integer, Integer> hm = new HashMap<>(); long sum = 0; for (int x : cycle) { int c = count(x, -1) - 1; sum += c + 1; hm.put(x, c + 1); // System.out.println(c + " " + x); ans += c * 1l * (c + 1)/2; } // System.out.println(sum); // ans += cycle.size() * 1l * (cycle.size() - 1); for (int x : cycle) { long g = sum - hm.get(x); // System.out.println(g*(hm.get(x))); // System.out.println(sum); ans += g * (hm.get(x) ); // ans += hm.get(x) - 1; } pw.println(ans); } pw.flush(); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
fc2824ad39d36ad35b151a7bdf9b1ce8
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.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.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class EX1_8 { static ArrayList<Integer>[] g; static boolean[] vis; static int[] parent; static ArrayList<Integer> cycle; static HashSet<Integer> hs; static boolean dfs(int u, int pa) { vis[u] = true; parent[u] = pa; for (int v : g[u]) { if (v == pa) continue; if (vis[v]) { int x = u; while (x != v) { cycle.add(x); hs.add(x); x = parent[x]; } hs.add(x); cycle.add(x); return true; } if (dfs(v, u)) return true; } return false; } static long ans; static int count(int u, int pa) { int c = 1; for (int v : g[u]) { if (v == pa || hs.contains(v)) continue; c += count(v, u); } return c; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); g = new ArrayList[n]; parent = new int[n]; for (int i = 0; i < g.length; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < g.length; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int u = Integer.parseInt(st.nextToken()) - 1; int v = Integer.parseInt(st.nextToken()) - 1; g[u].add(v); g[v].add(u); } vis = new boolean[n]; cycle = new ArrayList<>(); hs = new HashSet<>(); dfs(0, -1); long ans = 0; // System.out.println(cycle); HashMap<Integer, Integer> hm = new HashMap<>(); long sum = 0; for (int x : cycle) { int c = count(x, -1); sum += c; // System.out.println(c + " " + x); ans += c * 1l * (c - 1)/2; ans+=(n-(c))*1l*(c); } pw.println(ans); } pw.flush(); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
98049cce7290e4a3fcdd68c6bb3d32a1
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; public class E1454 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); ArrayList<Integer>[] adjList = new ArrayList[n]; for (int i = 0; i < adjList.length; i++) { adjList[i] = new ArrayList<Integer>(); } int[] deg = new int[n]; for (int i = 0; i < n; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; deg[u]++; deg[v]++; adjList[u].add(v); adjList[v].add(u); } int[] w = new int[n]; Arrays.fill(w, 1); Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { if (deg[i] == 1) { q.add(i); } } while (!q.isEmpty()) { int cur = q.poll(); for (int x : adjList[cur]) { if (deg[x] > 1) { w[x] += w[cur]; w[cur] = 0; deg[cur]--; if (--deg[x] == 1) { q.add(x); } break; } } // System.out.println(q); // System.out.println(Arrays.toString(w)); } ArrayList<Integer> al = new ArrayList<Integer>(); for (int x : w) { if (x != 0) { al.add(x); } } long ans = 0; // System.out.println(al); for (int x : al) { ans += 1l * x * (x - 1) / 2; ans += 1l * x * (n - x); } pw.println(ans); } pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
64adc8d9baa92cb8aaf3fff5e19981a4
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static BufferedReader bf; public static long[][] dp; public static void main(String[] args) throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int T = Integer.parseInt(bf.readLine()); while (T-- > 0) { String[] ip = bf.readLine().split(" "); int n = Integer.parseInt(ip[0]); ArrayList<HashSet<Integer>> graph = new ArrayList<>(); for (int i = 0; i <= n; i++) { graph.add(new HashSet<>()); } for (int i = 0; i < n; i++) { ip = bf.readLine().split(" "); int from = Integer.parseInt(ip[0]); int to = Integer.parseInt(ip[1]); graph.get(from).add(to); graph.get(to).add(from); } Queue<Integer> q = new LinkedList<>(); boolean[] vis = new boolean[n + 1]; int[] count = new int[n + 1]; ArrayList<Integer> cycleNodes = new ArrayList<>(); Arrays.fill(count, 1); for (int i = 1; i <= n; i++) { if (!vis[i]) addAllLeaves(i, graph, vis, q); } if (q.size() > 0) { while (!q.isEmpty()) { int leaf = q.poll(); int parent = graph.get(leaf).iterator().next(); graph.get(parent).remove(leaf); graph.get(leaf).clear(); count[parent] += count[leaf]; count[leaf] = 0; if (graph.get(parent).size() == 1) q.add(parent); } } long ans = 0; for (int i = 1; i <=n; i++) { long cnt = count[i]; ans += (cnt * (cnt - 1)) / 2 + cnt * (n - cnt); } out.println(ans); } out.flush(); } private static void addAllLeaves(int curr, ArrayList<HashSet<Integer>> graph, boolean[] vis, Queue<Integer> q) { if (vis[curr]) return; vis[curr] = true; if (graph.get(curr).size() == 1) { q.add(curr); } else { for (int neigh : graph.get(curr)) { addAllLeaves(neigh, graph, vis, q); } } } private static int[] readArray(int startIndex) throws IOException { String[] ip = bf.readLine().split(" "); int size = ip.length; int j = -1; if (startIndex == 1) { j = 0; size += 1; } int[] arr = new int[size]; for (String str : ip) arr[++j] = Integer.parseInt(str); return arr; } private static long[] readLongArray(int startIndex) throws IOException { String[] ip = bf.readLine().split(" "); int size = ip.length; int j = -1; if (startIndex == 1) { j = 0; size += 1; } long[] arr = new long[size]; for (String str : ip) arr[++j] = Long.parseLong(str); return arr; } } // 1010
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
ccf8769157580b3bc03d95b4a7bd17e8
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { private static FastReader fr = new FastReader(); private static Helper hp = new Helper(); private static StringBuilder result = new StringBuilder(); public static void main(String[] args) { Task solver = new Task(); solver.solve(); } static class Task { private List<Integer>[] graph; private Set<Integer> cycleVertices; private boolean isCycle(int vertex, boolean[] visited, int parent, Stack<Integer> path){ if(visited[vertex]) return false; visited[vertex] = true; path.push(vertex); List<Integer> neighbors = graph[vertex]; for(Integer neighbor : neighbors){ if(neighbor.compareTo(parent) != 0){ if(visited[neighbor]){ cycleVertices.add(neighbor); while (!path.isEmpty() && path.peek().compareTo(neighbor) != 0){ cycleVertices.add(path.pop()); } return true; } else{ boolean isCycle = isCycle(neighbor, visited, vertex, path); if(isCycle) return true; } } } path.pop(); return false; } private int getChildNodeCount(int vertex, boolean[] visited){ if(visited[vertex]) return 0; visited[vertex] = true; int count = 1; List<Integer> neighbors = graph[vertex]; for (Integer neighbor : neighbors) { if(cycleVertices.contains(neighbor)) continue; count += getChildNodeCount(neighbor, visited); } return count; } public void solve() { int tc = fr.ni(); while (tc-- > 0){ int vertices = fr.ni(); graph = new ArrayList[vertices]; cycleVertices = new HashSet<>(); for(int i=0; i<vertices; i++) { graph[i] = new ArrayList<>(); } for(int i=0; i<vertices; i++){ int u = fr.ni()-1; int v = fr.ni()-1; graph[u].add(v); graph[v].add(u); } boolean[] visited = new boolean[vertices]; isCycle(0, visited, -1, new Stack<>()); long ans = computeNcR(vertices, 2); Integer[] cycleVerticesList = cycleVertices.toArray(new Integer[]{}); visited = new boolean[vertices]; int[] childNodes = new int[vertices]; for(int i=0; i<cycleVerticesList.length; i++){ childNodes[cycleVerticesList[i]] = getChildNodeCount(cycleVerticesList[i], visited); } long count = 0; for(int i=0; i<cycleVerticesList.length; i++){ count += childNodes[cycleVerticesList[i]]; ans += childNodes[cycleVerticesList[i]] * (vertices - count); } // for(int i=0; i<cycleVerticesList.length; i++){ // long count = 0; // for(int j=i+1; j<cycleVerticesList.length; j++){ // count += childNodes[cycleVerticesList[j]]; // } // long sub = childNodes[cycleVerticesList[i]] * count; // ans += sub; // } result.append(ans).append("\n"); } System.out.println(result); } } static class Helper { public int[] ipArrInt(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fr.ni(); return arr; } public long[] ipArrLong(int n, int si) { long[] arr = new long[n]; for (int i = si; i < n; i++) arr[i] = fr.nl(); return arr; } } private static long computeNcR(int n, int r){ long p = 1, k = 1; if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; long m = gcd(p, k); p /= m; k /= m; n--; r--; } } return p; } private static long gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } static class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; private static PrintWriter pw; public FastReader() { reader = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); 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 String rl() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = fr.ni(); return arr; } public void print(String str) { pw.print(str); pw.flush(); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
0cec3f222342c22401cd42e1cb0cbe19
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { private static FastReader fr = new FastReader(); private static Helper hp = new Helper(); private static StringBuilder result = new StringBuilder(); public static void main(String[] args) { Task solver = new Task(); solver.solve(); } static class Task { private List<Integer>[] graph; private Set<Integer> cycleVertices; private boolean isCycle(int vertex, boolean[] visited, int parent, Stack<Integer> path){ if(visited[vertex]) return false; visited[vertex] = true; path.push(vertex); List<Integer> neighbors = graph[vertex]; for(Integer neighbor : neighbors){ if(neighbor.compareTo(parent) != 0){ if(visited[neighbor]){ cycleVertices.add(neighbor); while (!path.isEmpty() && path.peek().compareTo(neighbor) != 0){ cycleVertices.add(path.pop()); } return true; } else{ boolean isCycle = isCycle(neighbor, visited, vertex, path); if(isCycle) return true; } } } path.pop(); return false; } private int getChildNodeCount(int vertex, boolean[] visited){ if(visited[vertex]) return 0; visited[vertex] = true; int count = 1; List<Integer> neighbors = graph[vertex]; for (Integer neighbor : neighbors) { if(cycleVertices.contains(neighbor)) continue; count += getChildNodeCount(neighbor, visited); } return count; } public void solve() { int tc = fr.ni(); while (tc-- > 0){ int vertices = fr.ni(); graph = new ArrayList[vertices]; cycleVertices = new HashSet<>(); for(int i=0; i<vertices; i++) { graph[i] = new ArrayList<>(); } for(int i=0; i<vertices; i++){ int u = fr.ni()-1; int v = fr.ni()-1; graph[u].add(v); graph[v].add(u); } boolean[] visited = new boolean[vertices]; isCycle(0, visited, -1, new Stack<>()); long ans = computeNcR(vertices, 2); Integer[] cycleVerticesList = cycleVertices.toArray(new Integer[]{}); visited = new boolean[vertices]; int[] childNodes = new int[vertices]; for(int i=0; i<cycleVerticesList.length; i++){ childNodes[cycleVerticesList[i]] = getChildNodeCount(cycleVerticesList[i], visited); } long count = 0; for(int i=0; i<cycleVerticesList.length; i++){ count += childNodes[cycleVerticesList[i]]; ans = ans + childNodes[cycleVerticesList[i]] * (vertices - count); } // for(int i=0; i<cycleVerticesList.length; i++){ // long count = 0; // for(int j=i+1; j<cycleVerticesList.length; j++){ // count += childNodes[cycleVerticesList[j]]; // } // long sub = childNodes[cycleVerticesList[i]] * count; // ans += sub; // } result.append(ans).append("\n"); } System.out.println(result); } } static class Helper { public int[] ipArrInt(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fr.ni(); return arr; } public long[] ipArrLong(int n, int si) { long[] arr = new long[n]; for (int i = si; i < n; i++) arr[i] = fr.nl(); return arr; } } private static long computeNcR(int n, int r){ long p = 1, k = 1; if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; long m = gcd(p, k); p /= m; k /= m; n--; r--; } } return p; } private static long gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } static class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; private static PrintWriter pw; public FastReader() { reader = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); 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 String rl() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = fr.ni(); return arr; } public void print(String str) { pw.print(str); pw.flush(); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
ed50106284de8890746ecece4b656463
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
// Don't place your source in a package import java.util.*; import java.lang.*; import java.io.*; import java.math.*; // Please name your class Main public class Main { //static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); /*static int read() throws IOException { in.nextToken(); return (int) in.nval; } static String readString() throws IOException { in.nextToken(); return in.sval; }*/ static Scanner in = new Scanner(System.in); public static void main (String[] args) throws java.lang.Exception { //InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int T=Int(); for(int t=0;t<T;t++){ int n=Int(); List<Integer>adjecent[]=new ArrayList[n]; for(int i=0;i<n;i++){ adjecent[i]=new ArrayList<>(); } for(int i=0;i<n;i++){ int v1=Int()-1; int v2=Int()-1; adjecent[v1].add(v2); adjecent[v2].add(v1); } Solution sol=new Solution(); sol.solution(adjecent); } out.flush(); } public static long Long(){ return in.nextLong(); } public static int Int(){ return in.nextInt(); } public static String Str(){ return in.next(); } } class Solution{ //constant variable final int MAX=Integer.MAX_VALUE; final int MIN=Integer.MIN_VALUE; //Set<Integer>adjecent[]; ////////////////////////////// public void fastprint(PrintWriter out,String s){ out.print(s); } public void fastprintln(PrintWriter out,String s){ out.println(s); } boolean visit[]; List<Integer>adjecent[]; int time=1; int low[]; HashSet<Integer>cycle=new HashSet<>(); int cnt=0; public void solution(List<Integer>adjecent[]){ this.adjecent=adjecent; long n=adjecent.length; visit=new boolean[(int)(n)]; low=new int[(int)(n)]; long res=(n*(n-1))/2; //tree count tarjan(-1,0); Map<Integer,HashSet<Integer>>map=new HashMap<>(); for(int i=0;i<low.length;i++){ if(!map.containsKey(low[i])){ map.put(low[i],new HashSet<>()); map.get(low[i]).add(i); }else{ map.get(low[i]).add(i); cycle=map.get(low[i]); } } Arrays.fill(visit,false); long other=0; for(Integer point:cycle){ visit[point]=true; cnt=1; dfs(point); //msg(point+" "+cnt); long reacheable=cnt*(n-cnt); other+=reacheable; } msg(res+(other/2)+""); } public void dfs(int root){ List<Integer>next=adjecent[root]; for(int c:next){ if(visit[c]||cycle.contains(c))continue; visit[c]=true; cnt++; dfs(c); } } public void tarjan(int parent,int root){ List<Integer>childs=adjecent[root]; low[root]=time++; visit[root]=true; for(int c:childs){ if(!visit[c]){ tarjan(root,c); low[root]=Math.min(low[root],low[c]); }else{ if(c!=parent){//met ancestor low[root]=Math.min(low[root],low[c]); } } } } /*class LCA{ int p1,p2; boolean visit[]; int res=-1; boolean good=false; public LCA(int p1,int p2){ this.p1=p1;this.p2=p2; visit=new boolean[adjecent.length]; } public boolean dfs(int root){ visit[root]=true; List<Integer>next=adjecent[root]; boolean ans=false; if(root==p1||root==p2){ ans=true; } int cnt=0; for(int c:next){ if(visit[c])continue; boolean v=dfs(c); ans|=v; if(v)cnt++; } if(cnt==2){ if(!good){ good=true; res=root; } } else if(cnt==1){ if(!good&&(root==p1||root==p2)){ good=true; res=root; } } return ans; } }*/ /*public void delete(Dnode node){ Dnode pre=node.pre; Dnode next=node.next; pre.next=next; next.pre=pre; map.remove(node.v); } public void add(int v){ Dnode node=new Dnode(v); Dnode pre=tail.pre; pre.next=node; node.pre=pre; node.next=tail; tail.pre=node; map.put(v,node); } class Dnode{ Dnode next=null; Dnode pre=null; int v; public Dnode(int v){ this.v=v; } }*/ public String tobin(int i){ return Integer.toBinaryString(i); } public void reverse(int A[]){ List<Integer>l=new ArrayList<>(); for(int i:A)l.add(i); Collections.reverse(l); for(int i=0;i<A.length;i++){ A[i]=l.get(i); } } public void sort(int A[]){ Arrays.sort(A); } public void swap(int A[],int l,int r){ int t=A[l]; A[l]=A[r]; A[r]=t; } public long C(long fact[],int i,int j){ // C(20,3)=20!/(17!*3!) // take a/b where a=20! b=17!*3! if(j>i)return 1; if(j<=0)return 1; long mod=998244353; long a=fact[i]; long b=((fact[i-j]%mod)*(fact[j]%mod))%mod; BigInteger B= BigInteger.valueOf(b); long binverse=B.modInverse(BigInteger.valueOf(mod)).longValue(); return ((a)*(binverse%mod))%mod; } public long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } //map operation public void put(Map<Integer,Integer>map,int i){ if(!map.containsKey(i))map.put(i,0); map.put(i,map.get(i)+1); } public void delete(Map<Integer,Integer>map,int i){ map.put(i,map.get(i)-1); if(map.get(i)==0)map.remove(i); } /*public void tarjan(int p,int r){ if(cut)return; List<Integer>childs=adjecent[r]; dis[r]=low[r]=time; time++; //core for tarjan int son=0; for(int c:childs){ if(ban==c||c==p)continue; if(dis[c]==-1){ son++; tarjan(r,c); low[r]=Math.min(low[r],low[c]); if((r==root&&son>1)||(low[c]>=dis[r]&&r!=root)){ cut=true; return; } }else{ if(c!=p){ low[r]=Math.min(low[r],dis[c]); } } } }*/ //helper function I would use public void remove(Map<Integer,Integer>map,int i){ map.put(i,map.get(i)-1); if(map.get(i)==0)map.remove(i); } public void ascii(String s){ for(char c:s.toCharArray()){ System.out.print((c-'a')+" "); } msg(""); } public int flip(int i){ if(i==0)return 1; else return 0; } public boolean[] primes(int n){ boolean A[]=new boolean[n+1]; for(int i=2;i<=n;i++){ if(A[i]==false){ for(int j=i+i;j<=n;j+=i){ A[j]=true; } } } return A; } public void msg(String s){ System.out.println(s); } public void msg1(String s){ System.out.print(s); } public int[] kmpPre(String p){ int pre[]=new int[p.length()]; int l=0,r=1; while(r<p.length()){ if(p.charAt(l)==p.charAt(r)){ pre[r]=l+1; l++;r++; }else{ if(l==0)r++; else l=pre[l-1]; } } return pre; } public boolean isP(String s){ int l=0,r=s.length()-1; while(l<r){ if(s.charAt(l)!=s.charAt(r))return false; l++;r--; } return true; } public int find(int nums[],int x){//union find => find method if(nums[x]==x)return x; int root=find(nums,nums[x]); nums[x]=root; return root; } public int[] copy1(int A[]){ int a[]=new int[A.length]; for(int i=0;i<a.length;i++)a[i]=A[i]; return a; } public void printd1(double A[]){ for(double i:A)System.out.print(i+" "); System.out.println(); } public void print1(int A[]){ for(long i:A)System.out.print(i+" "); System.out.println(); } public void print2(int A[][]){ for(int i=0;i<A.length;i++){ for(int j=0;j<A[0].length;j++){ System.out.print(A[i][j]+" "); }System.out.println(); } } public int min(int a,int b){ return Math.min(a,b); } public int[][] matrixdp(int[][] grid) { if(grid.length==0)return new int[][]{}; int res[][]=new int[grid.length][grid[0].length]; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ res[i][j]=grid[i][j]+get(res,i-1,j)+get(res,i,j-1)-get(res,i-1,j-1); } } return res; } public int get(int grid[][],int i,int j){ if(i<0||j<0||i>=grid.length||j>=grid[0].length)return 0; return grid[i][j]; } public int[] suffixArray(String s){ int n=s.length(); Suffix A[]=new Suffix[n]; for(int i=0;i<n;i++){ A[i]=new Suffix(i,s.charAt(i)-'a',0); } for(int i=0;i<n;i++){ if(i==n-1){ A[i].next=-1; }else{ A[i].next=A[i+1].rank; } } Arrays.sort(A); for(int len=4;len<A.length*2;len<<=1){ int in[]=new int[A.length]; int rank=0; int pre=A[0].rank; A[0].rank=rank; in[A[0].index]=0; for(int i=1;i<A.length;i++){//rank for the first two letter if(A[i].rank==pre&&A[i].next==A[i-1].next){ pre=A[i].rank; A[i].rank=rank; }else{ pre=A[i].rank; A[i].rank=++rank; } in[A[i].index]=i; } for(int i=0;i<A.length;i++){ int next=A[i].index+len/2; if(next>=A.length){ A[i].next=-1; }else{ A[i].next=A[in[next]].rank; } } Arrays.sort(A); } int su[]=new int[A.length]; for(int i=0;i<su.length;i++){ su[i]=A[i].index; } return su; } } //suffix array Struct class Suffix implements Comparable<Suffix>{ int index; int rank; int next; public Suffix(int i,int rank,int next){ this.index=i; this.rank=rank; this.next=next; } @Override public int compareTo(Suffix other) { if(this.rank==other.rank){ return this.next-other.next; } return this.rank-other.rank; } public String toString(){ return this.index+" "+this.rank+" "+this.next+" "; } } class Wrapper implements Comparable<Wrapper>{ int spf;int cnt; public Wrapper(int spf,int cnt){ this.spf=spf; this.cnt=cnt; } @Override public int compareTo(Wrapper other) { return this.spf-other.spf; } } class Node{//what the range would be for that particular node boolean state=false; int l=0,r=0; int ll=0,rr=0; public Node(boolean state){ this.state=state; } } class Seg1{ int A[]; public Seg1(int A[]){ this.A=A; } public void update(int left,int right,int val,int s,int e,int id){ if(left<0||right<0||left>right)return; if(left==s&&right==e){ A[id]+=val; return; } int mid=s+(e-s)/2; //[s,mid] [mid+1,e] if(left>=mid+1){ update(left,right,val,mid+1,e,id*2+2); }else if(right<=mid){ update(left,right,val,s,mid,id*2+1); }else{ update(left,mid,val,s,mid,id*2+1); update(mid+1,right,val,mid+1,e,id*2+2); } } public int query(int i,int add,int s,int e,int id){ if(s==e&&i==s){ return A[id]+add; } int mid=s+(e-s)/2; //[s,mid] [mid+1,e] if(i>=mid+1){ return query(i,A[id]+add,mid+1,e,id*2+2); }else{ return query(i,A[id]+add,s,mid,id*2+1); } } } class MaxFlow{ public static List<Edge>[] createGraph(int nodes) { List<Edge>[] graph = new List[nodes]; for (int i = 0; i < nodes; i++) graph[i] = new ArrayList<>(); return graph; } public static void addEdge(List<Edge>[] graph, int s, int t, int cap) { graph[s].add(new Edge(t, graph[t].size(), cap)); graph[t].add(new Edge(s, graph[s].size() - 1, 0)); } static boolean dinicBfs(List<Edge>[] graph, int src, int dest, int[] dist) { Arrays.fill(dist, -1); dist[src] = 0; int[] Q = new int[graph.length]; int sizeQ = 0; Q[sizeQ++] = src; for (int i = 0; i < sizeQ; i++) { int u = Q[i]; for (Edge e : graph[u]) { if (dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1; Q[sizeQ++] = e.t; } } } return dist[dest] >= 0; } static int dinicDfs(List<Edge>[] graph, int[] ptr, int[] dist, int dest, int u, int f) { if (u == dest) return f; for (; ptr[u] < graph[u].size(); ++ptr[u]) { Edge e = graph[u].get(ptr[u]); if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { int df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f)); if (df > 0) { e.f += df; graph[e.t].get(e.rev).f -= df; return df; } } } return 0; } public static int maxFlow(List<Edge>[] graph, int src, int dest) { int flow = 0; int[] dist = new int[graph.length]; while (dinicBfs(graph, src, dest, dist)) { int[] ptr = new int[graph.length]; while (true) { int df = dinicDfs(graph, ptr, dist, dest, src, Integer.MAX_VALUE); if (df == 0) break; flow += df; } } return flow; } } class Edge { int t, rev, cap, f; public Edge(int t, int rev, int cap) { this.t = t; this.rev = rev; this.cap = cap; } } class Seg{ int l,r; int min=Integer.MAX_VALUE; Seg left=null,right=null; int tree[]; public Seg(int l,int r){ this.l=l; this.r=r; if(l!=r){ int mid=l+(r-l)/2; if(l<=mid)left=new Seg(l,mid); if(r>=mid+1)right=new Seg(mid+1,r); if(left!=null)min=Math.min(left.min,min); if(right!=null)min=Math.min(right.min,min); }else{ min=tree[l]; } } public int query(int s,int e){ if(l==s&&r==e){ return min; } int mid=l+(r-l)/2; //left : to mid-1, if(e<=mid){ return left.query(s,e); } else if(s>=mid+1){ return right.query(s,e); }else{ return Math.min(left.query(s,mid),right.query(mid+1,e)); } } public void update(int index){ if(l==r){ min=tree[l]; return; } int mid=l+(r-l)/2; if(index<=mid){ left.update(index); }else{ right.update(index); } this.min=Math.min(left.min,right.min); } } class Fenwick { int tree[];//1-index based int A[]; int arr[]; public Fenwick(int[] A) { this.A=A; arr=new int[A.length]; tree=new int[A.length+1]; int sum=0; for(int i=0;i<A.length;i++){ update(i,A[i]); } } public void update(int i, int val) { arr[i]+=val; i++; while(i<tree.length){ tree[i]+=val; i+=(i&-i); } } public int sumRange(int i, int j) { return pre(j+1)-pre(i); } public int pre(int i){ int sum=0; while(i>0){ sum+=tree[i]; i-=(i&-i); } return sum; } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
8bcce92925f1f00c67ca75f4cf3e23ed
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class CF686e { static PrintWriter pw; static class FastReader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar, numChars; public FastReader() { this(System.in); } public FastReader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long l() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int i() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double d() throws IOException { return Double.parseDouble(next()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void scanIntArr(int[] arr) { for (int li = 0; li < arr.length; ++li) arr[li] = i(); } public void scanIntIndexArr(int[] arr) { for (int li = 0; li < arr.length; ++li) { arr[li] = i() - 1; } } public void printIntArr(int[] arr) { for (int li = 0; li < arr.length; ++li) pw.print(arr[li] + " "); pw.println(); } public void printLongArr(long[] arr) { for (int li = 0; li < arr.length; ++li) pw.print(arr[li] + " "); pw.println(); } public void scanLongArr(long[] arr) { for (int i = 0; i < arr.length; ++i) { arr[i] = l(); } } public void shuffle(int[] arr) { for (int i = arr.length; i > 0; --i) { int r = (int) (Math.random() * i); int temp = arr[i - 1]; arr[i - 1] = arr[r]; arr[r] = temp; } } public int findMax(int[] arr) { return Arrays.stream(arr).max().getAsInt(); } } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); pw = new PrintWriter(System.out); int i, j, n, m, temp, t, k; t = fr.i(); while (t-- > 0) { long ans=0; n = fr.i(); ArrayList<Set<Integer>> g = new ArrayList<>(); for(i=0;i<=n;i++) g.add(new HashSet<>()); for(i=0;i<n;i++) { int a = fr.i(); int b = fr.i(); g.get(a).add(b); g.get(b).add(a); } int children[] = new int[n+1]; Arrays.fill(children, 1); Queue<Integer> q = new LinkedList<>(); for(i=1;i<=n;i++) { if(g.get(i).size()==1) { q.add(i); } } while(!q.isEmpty()) { int val = q.poll(); for(Integer ele : g.get(val)) { children[ele]+=children[val]; children[val]=0; g.get(ele).remove(val); if(g.get(ele).size()==1) q.add(ele); } g.get(val).clear(); } for(i=1;i<=n;i++) { if(children[i]>0) { ans += (children[i]*1L*(children[i]-1))/2; ans += (children[i]*1L*(n-children[i])); } } pw.println(ans); } pw.flush(); pw.close(); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
e266d068b576098e5aca95f99db8bb61
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.stream.Collectors; public class Main { static FastScanner sc; static PrintWriter pw; static final int INF = 1000000000; public static Integer cycle_end, cycle_st; public static int[] p; public static int[] cl; public static List<List<Integer>> g; public static boolean[] marked; static boolean dfs(int v ) { cl[v] = 1; for(int i = 0; i < g.get(v).size(); ++i) { int to = g.get(v).get(i); if(cl[to] == 0) { p[to] = v; if(dfs(to)) return true; } else if(cl[to] == 1 && p[v] != to){ cycle_end = v; cycle_st = to; return true; } } cl[v] = 2; return false; } static int dfs2(int v, Set<Integer> cycle) { marked[v] = true; int count = 0; for(int i = 0; i < g.get(v).size(); ++i) { int to = g.get(v).get(i); if(!cycle.contains(to) && !marked[to]) { count += dfs2(to, cycle); } } return count + 1; } public static void main(String[] args) throws IOException { sc = new FastScanner(System.in); pw = new PrintWriter(System.out); int ff = sc.nextInt(); for(int tt = 0; tt < ff; ++tt) { int n = sc.nextInt(); g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); for(int i = 0; i < n; ++i) { int x = sc.nextInt(), y = sc.nextInt(); x--; y--; g.get(x).add(y); g.get(y).add(x); } p = new int[n + 1]; cl = new int[n + 1]; Arrays.fill(p, -1); Arrays.fill(cl, 0); cycle_st = -1; for(int i = 0; i < n; ++i) if(dfs(i)) break; Set<Integer> cycle = new HashSet<>(); cycle.add(cycle_st); for(int v = cycle_end; v != cycle_st; v = p[v]) cycle.add(v); long sz = cycle.size(); long f = n - sz; marked = new boolean[n]; // pw.println(n + " " + f); long ans = 0; for(Integer v : cycle) { int qq = dfs2(v, cycle); ans += qq * 1l * (qq - 1) + (n - qq) * 2l * qq ; } pw.println(ans / 2); // pw.println(cycle); } pw.close(); } } class FastScanner { static StringTokenizer st = new StringTokenizer(""); static BufferedReader br; public FastScanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() throws IOException { while (!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()); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
cc9c2178b74268d968e0aa8fd264d2fa
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; public class Number_Into_Sequence { 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 void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); Set<Integer>[] graph = new Set[n]; for (int i = 0; i < n; ++i) { graph[i] = new HashSet<>(); } for (int i = 0; i < n; ++i) { int x = t.nextInt() - 1; int y = t.nextInt() - 1; graph[x].add(y); graph[y].add(x); } long[] count = new long[n]; Queue<Integer> queue = new LinkedList<>(); for (int i = 0; i < n; ++i) { if (graph[i].size() == 1) { queue.add(i); } count[i] = 1; } while (!queue.isEmpty()) { int from = queue.remove(); int to = -1; for (int val : graph[from]) { to = val; } graph[from].clear(); graph[to].remove(from); count[to] += count[from]; count[from] = 0; if (graph[to].size() == 1) queue.add(to); } long ans = 0; for (int i = 0; i < n; ++i) { ans += (count[i] * (count[i] - 1)) >> 1; ans += (n - count[i]) * count[i]; } o.println(ans); } o.flush(); o.close(); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
767a48f15c5c0f110f66c9f2da15ba01
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; public class Number_Into_Sequence { 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 void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); Set<Integer>[] graph = new Set[n]; color = new int[n]; parent = new int[n]; cycle_end = -1; cycle_start = -1; for (int i = 0; i < n; ++i) { graph[i] = new HashSet<>(); parent[i] = -1; } for (int i = 0; i < n; ++i) { int x = t.nextInt() - 1; int y = t.nextInt() - 1; graph[x].add(y); graph[y].add(x); } boolean[] vis = new boolean[n]; List<Long> count = new ArrayList<>(); find_cycle(graph); for (int i = 0; i < n; ++i) { if (!vis[i]) { Stack<Integer> stack = new Stack<>(); Set<Integer> cur = new HashSet<>(); vis[i] = true; stack.push(i); while (!stack.isEmpty()) { int v = stack.pop(); cur.add(v); for (int val : graph[v]) { if (!vis[val]) { stack.push(val); vis[val] = true; } } } count.add((long) cur.size()); } } long ans = 0; for (long v : count) { ans += (v * (v - 1)) >> 1; ans += (n - v) * v; } o.println(ans); } o.flush(); o.close(); } public static int color[]; public static int parent[]; public static int cycle_end; public static int cycle_start; private static boolean dfs(int v, int par, Set<Integer>[] graph) { color[v] = 1; for (int u : graph[v]) { if (u == par) continue; if (color[u] == 0) { parent[u] = v; if (dfs(u, parent[u], graph)) return true; } else if (color[u] == 1) { cycle_end = v; cycle_start = u; return true; } } color[v] = 2; return false; } public static void find_cycle(Set<Integer>[] graph) { int n = graph.length; List<Integer> cycle = new ArrayList<>(); for (int v = 0; v < n; v++) { if (color[v] == 0 && dfs(v, parent[v], graph)) break; } cycle.add(cycle_start); for (int v = cycle_end; v != cycle_start; v = parent[v]) cycle.add(v); cycle.add(cycle_start); for (int i = 0; i < cycle.size() - 1; ++i) { int x = cycle.get(i); int y = cycle.get(i + 1); graph[x].remove(y); graph[y].remove(x); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
7965bef62bd953d211225066b6ce9a97
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.util.*; import java.io.*; public class Number_Into_Sequence { 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 void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); Set<Integer>[] graph = new Set[n]; color = new int[n]; parent = new int[n]; cycle_end = -1; cycle_start = -1; for (int i = 0; i < n; ++i) { graph[i] = new HashSet<>(); parent[i] = -1; } for (int i = 0; i < n; ++i) { int x = t.nextInt() - 1; int y = t.nextInt() - 1; graph[x].add(y); graph[y].add(x); } long group[] = new long[n]; boolean[] vis = new boolean[n]; List<Long> count = new ArrayList<>(); find_cycle(graph); for (int i = 0; i < n; ++i) { if (!vis[i]) { Stack<Integer> stack = new Stack<>(); Set<Integer> cur = new HashSet<>(); vis[i] = true; stack.push(i); while (!stack.isEmpty()) { int v = stack.pop(); cur.add(v); for (int val : graph[v]) { if (!vis[val]) { stack.push(val); vis[val] = true; } } } for (int val : cur) { group[val] = cur.size(); } count.add((long) cur.size()); } } long ans = 0; for (int i = 0; i < n; ++i) { ans += (n - group[i]); } for (long v : count) { ans += (v * (v - 1)) >> 1; } o.println(ans); } o.flush(); o.close(); } public static int color[]; public static int parent[]; public static int cycle_end; public static int cycle_start; private static boolean dfs(int v, int par, Set<Integer>[] graph) { color[v] = 1; for (int u : graph[v]) { if (u == par) continue; if (color[u] == 0) { parent[u] = v; if (dfs(u, parent[u], graph)) return true; } else if (color[u] == 1) { cycle_end = v; cycle_start = u; return true; } } color[v] = 2; return false; } public static void find_cycle(Set<Integer>[] graph) { int n = graph.length; List<Integer> cycle = new ArrayList<>(); for (int v = 0; v < n; v++) { if (color[v] == 0 && dfs(v, parent[v], graph)) break; } cycle.add(cycle_start); for (int v = cycle_end; v != cycle_start; v = parent[v]) cycle.add(v); cycle.add(cycle_start); for (int i = 0; i < cycle.size() - 1; ++i) { int x = cycle.get(i); int y = cycle.get(i + 1); graph[x].remove(y); graph[y].remove(x); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
8aa9dc1684cd7acf8b2a822db4cf612f
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class CodeFor1 { public static void main(String[] args) throws IOException { // InputStream inputStream = new FileInputStream("input.txt"); // OutputStream outputStream = new FileOutputStream("output.txt"); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in.nextInt(), in, out); out.close(); } static class TaskA { long mod = (long)(1e9) + 7; long fact[]; int depth[]; int parentTable[][]; int degree[]; ArrayList<Integer> leaves; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; int diam = 0; long res = 0; public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException { while(testNumber-->0){ int n = in.nextInt(); ArrayList<ArrayList<Integer>> a = new ArrayList<>(); for(int i=0;i<=n;i++) a.add(new ArrayList<>()); for(int i=0;i<n;i++){ int u = in.nextInt(); int v = in.nextInt(); a.get(u).add(v); a.get(v).add(u); } ArrayList<Integer> b = new ArrayList<>(); // System.out.println(a); dfs(a , 1 , 0 , new int[n+1] , new boolean[n+1] , b); // System.out.println(b); boolean visited[] = new boolean[n+1]; for(int i=0;i<b.size();i++) visited[b.get(i)] = true; long ans = 0; int count = 0; for(int i : b){ // if(!visited[i]) // continue; // count++; res = 0; dfsNow(a , i , 0 , visited); ans += (res)*(res-1)/2 + res * (n-res); } // if(count < b.size()){ // ans += (b.size() - count) * (n - 1); // } out.println(ans); } } public void dfsNow(ArrayList<ArrayList<Integer>> a , int index , int parent , boolean visited[]){ visited[index] = true; res++; for(int i=0;i<a.get(index).size();i++){ if(visited[a.get(index).get(i)] || a.get(index).get(i) == parent) continue; dfsNow(a , a.get(index).get(i) , index , visited); } } public void dfs(ArrayList<ArrayList<Integer>> a , int index , int parent , int p[] , boolean visited[] , ArrayList<Integer> ans){ // height[index] = 1 + height[parent]; p[index] = parent; visited[index] = true; // for(int i=1;i<a.size();i++) // System.out.print(visited[i] + " "); // System.out.println(); // System.out.println(index + " " + parent); for(int i=0;i<a.get(index).size();i++){ if(ans.size()!=0) return; int v = a.get(index).get(i); if(parent == v) continue; if(visited[v]){ // System.out.println("inside"); // System.out.println(v + " " + index); // for(int j=1;j<p.length;j++) // System.out.print(p[j] + " "); // System.out.println(); ans.add(index); ans.add(v); int j = p[index]; while(j != v){ // System.out.println(j); ans.add(j); j = p[j]; } return; } if(ans.size() != 0) return; dfs(a , v , index , p , visited , ans); } } public int lower(ArrayList<Integer> a , int x){ if(a.size() == 0) return 0; if(a.get(a.size()-1) < x) return a.size(); int l = 0; int r = a.size()-1; while(l<=r){ int mid = (l+r)>>1; if(a.get(mid)>=x && (mid<1 || a.get(mid-1)<x)) return mid; else if(a.get(mid) < x) l = mid+1; else r = mid-1; } return -1; } public int distance(ArrayList<ArrayList<Integer>> a , int u , int v){ return depth[u]+depth[v] - 2*depth[lca(a , u , v)]; } public int lca(ArrayList<ArrayList<Integer>> a , int u , int v){ if(depth[v]<depth[u]){ int x = u; u = v; v = x; } int diff = depth[v] - depth[u]; for(int i=0;i<parentTable[v].length;i++){ // checking whether the ith bit is set in the diff variable if(((diff>>i)&1) == 1) v = parentTable[v][i]; } if(v == u) return v; for(int i=parentTable[v].length-1;i>=0;i--){ if(parentTable[u][i] != parentTable[v][i]){ v = parentTable[v][i]; u = parentTable[u][i]; } } return parentTable[u][0]; } public int[][] multiply(int a[][] , int b[][]){ int c[][] = new int[a.length][b[0].length]; for(int i=0;i<a.length;i++){ for(int j=0;j<b[0].length;j++){ for(int k=0;k<b.length;k++) c[i][j] += a[i][k]*b[k][j]; } } return c; } public int[][] multiply(int a[][] , int b[][] , int mod){ int c[][] = new int[a.length][b[0].length]; for(int i=0;i<a.length;i++){ for(int j=0;j<b[0].length;j++){ for(int k=0;k<b.length;k++){ c[i][j] += a[i][k]*b[k][j]; c[i][j]%=mod; } } } return c; } public int[][] pow(int a[][] , long b){ int res[][] = new int[a.length][a[0].length]; for(int i=0;i<a.length;i++) res[i][i] = 1; while(b>0){ if((b&1) == 1) res = multiply(res , a , 10); a = multiply(a , a , 10); b>>=1; } return res; } // for the min max problems public void build(int lookup[][] , int arr[], int n) { for (int i = 0; i < n; i++) lookup[i][0] = arr[i]; for (int j = 1; (1 << j) <= n; j++) { for (int i = 0; (i + (1 << j) - 1) < n; i++) { if (lookup[i][j - 1] > lookup[i + (1 << (j - 1))][j - 1]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1]; } } } public int query(int lookup[][] , int L, int R) { int j = (int)(Math.log(R - L + 1)/Math.log(2)); if (lookup[L][j] >= lookup[R - (1 << j) + 1][j]) return lookup[L][j]; else return lookup[R - (1 << j) + 1][j]; } // for printing purposes public void print1d(int a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); } public void print1d(long a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); } public void print2d(int a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } // out.println(); } public void print2d(long a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } // out.println(); } public void sieve(int a[]){ a[0] = a[1] = 1; int i; for(i=2;i*i<=a.length;i++){ if(a[i] != 0) continue; a[i] = i; for(int k = (i)*(i);k<a.length;k+=i){ if(a[k] != 0) continue; a[k] = i; } } } public long nCrPFermet(int n , int r , long p){ if(r==0) return 1l; // long fact[] = new long[n+1]; // fact[0] = 1; // for(int i=1;i<=n;i++) // fact[i] = (i*fact[i-1])%p; long modInverseR = pow(fact[r] , p-2 , p); long modInverseNR = pow(fact[n-r] , p-2 , p); long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p; return w; } public long pow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { long x = b&1; if (x == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } public long pow(long a, long b) { long res = 1; while (b > 0) { long x = b&1; if (x == 1) res = res * a; a = a * a; b >>= 1; } return res; } public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) { if (start > end) { return; } int mid = (start + end) / 2; a.add(mid); sortedArrayToBST(a, start, mid - 1); sortedArrayToBST(a, mid + 1, end); } class Combine{ int value; int delete; Combine(int val , int delete){ this.value = val; this.delete = delete; } } class Sort2 implements Comparator<Combine>{ public int compare(Combine a , Combine b){ if(a.value > b.value) return 1; else if(a.value == b.value && a.delete>b.delete) return 1; else if(a.value == b.value && a.delete == b.delete) return 0; return -1; } } public int lowerLastBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>=x) return -1; if(a.get(r)<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid-1)<x) return mid-1; else if(a.get(mid)>=x) r = mid-1; else if(a.get(mid)<x && a.get(mid+1)>=x) return mid; else if(a.get(mid)<x && a.get(mid+1)<x) l = mid+1; } return mid; } public int upperFirstBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>x) return l; if(a.get(r)<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid+1)>x) return mid+1; else if(a.get(mid)<=x) l = mid+1; else if(a.get(mid)>x && a.get(mid-1)<=x) return mid; else if(a.get(mid)>x && a.get(mid-1)>x) r = mid-1; } return mid; } public int lowerLastBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>=x) return -1; if(a[r]<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid-1]<x) return mid-1; else if(a[mid]>=x) r = mid-1; else if(a[mid]<x && a[mid+1]>=x) return mid; else if(a[mid]<x && a[mid+1]<x) l = mid+1; } return mid; } public int upperFirstBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>x) return l; if(a[r]<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid+1]>x) return mid+1; else if(a[mid]<=x) l = mid+1; else if(a[mid]>x && a[mid-1]<=x) return mid; else if(a[mid]>x && a[mid-1]>x) r = mid-1; } return mid; } public long log(float number , int base){ return (long) Math.ceil((Math.log(number) / Math.log(base)) + 1e-9); } public long gcd(long a , long b){ if(a<b){ long c = b; b = a; a = c; } while(b!=0){ long c = a; a = b; b = c%a; } return a; } public long[] gcdEx(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdEx(q, p % q); long d = vals[0]; long a = vals[2]; long b = vals[1] - (p / q) * vals[2]; // 0->gcd 1->xValue 2->yValue return new long[] { d, a, b }; } public void sievePhi(int a[]){ a[0] = 0; a[1] = 1; for(int i=2;i<a.length;i++) a[i] = i-1; for(int i=2;i<a.length;i++) for(int j = 2*i;j<a.length;j+=i) a[j] -= a[i]; } public void lcmSum(long a[]){ int sievePhi[] = new int[(int)1e6 + 1]; sievePhi(sievePhi); a[0] = 0; for(int i=1;i<a.length;i++) for(int j = i;j<a.length;j+=i) a[j] += (long)i*sievePhi[i]; } } 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\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
4d96bc533519b93d47f42f51ae3da67b
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; // graph, dfs,bfs, get connected components,iscycle, isbipartite, dfs on trees public class scratch_25 { static class Graph{ public static class Vertex{ HashMap<Integer,Integer> nb= new HashMap<>(); // for neighbours of each vertex } public static HashMap<Integer,Vertex> vt; // for vertices(all) public Graph(){ vt= new HashMap<>(); } public static int numVer(){ return vt.size(); } public static boolean contVer(int ver){ return vt.containsKey(ver); } public static void addVer(int ver){ Vertex v= new Vertex(); vt.put(ver,v); } public class Pair{ int vname; ArrayList<Integer> psf= new ArrayList<>(); // path so far int dis; int col; } public static void addEdge(int ver1, int ver2, int weight){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } Vertex v1= vt.get(ver1); Vertex v2= vt.get(ver2); v1.nb.put(ver2,weight); // if previously there is an edge, then this replaces that edge v2.nb.put(ver1,weight); } public static void delEdge(int ver1, int ver2){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } vt.get(ver1).nb.remove(ver2); vt.get(ver2).nb.remove(ver1); } public static void delVer(int ver){ if(!vt.containsKey(ver)){ return; } Vertex v1= vt.get(ver); ArrayList<Integer> arr= new ArrayList<>(v1.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); vt.get(s).nb.remove(ver); } vt.remove(ver); } static boolean done[]; static int parent[]; static ArrayList<Integer>vals= new ArrayList<>(); public static boolean isCycle(int i){ Stack<Integer>stk= new Stack<>(); stk.push(i); while(!stk.isEmpty()){ int x= stk.pop(); vals.add(x); // System.out.print("current="+x+" stackinit="+stk); if(!done[x]){ done[x]=true; } else if(done[x] ){ return true; } ArrayList<Integer>ar= new ArrayList<>(vt.get(x).nb.keySet()); for (int j = 0; j <ar.size() ; j++) { if(parent[x]!=ar.get(j)){ parent[ar.get(j)]=x; stk.push(ar.get(j)); } } // System.out.println(" stackfin="+stk); } return false; } public static long dfs(int v,Set<Integer>cycle){ Set<Integer>vis=new HashSet<>(); Stack<Integer>stk= new Stack<>(); stk.add(v); long count=0; while(!stk.isEmpty()){ int x= stk.pop(); count++; vis.add(x); ArrayList<Integer>ar= new ArrayList<>(vt.get(x).nb.keySet()); for (int i = 0; i <ar.size() ; i++) { int y= ar.get(i); if(!cycle.contains(y) && !vis.contains(y)){ stk.push(y); } } } return count; } } // int count=0; //static long count=0; static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, or negative after MOD int t= Reader.nextInt(); for (int tt = 0; tt <t ; tt++) { int n= Reader.nextInt(); Graph g= new Graph(); g.done= new boolean[n+1]; g.parent= new int[n+1]; for (int i = 1; i <=n ; i++) { g.addVer(i); } for (int i = 0; i <n ; i++) { g.addEdge(Reader.nextInt(),Reader.nextInt(),1); } g.isCycle(1); // System.out.println("----------------------------"); // System.out.println(g.vals); // System.out.println("parent="+Arrays.toString(g.parent)); int x= g.vals.get(g.vals.size()-1); Set<Integer>cycle= new HashSet<>(); cycle.add(x); int num=g.parent[x]; while(num!=x){ cycle.add(num); num= g.parent[num]; } // System.out.println("cycle="+cycle); long q= (long)n; long ans= q*(q-1); for (int val: cycle) { long numpy=g.dfs(val,cycle); // System.out.println("val="+val+"num="+num); ans-=(numpy)*(numpy-1)/2; } out.append(ans+"\n"); } out.flush(); out.close(); } public static void divisors(long num, ArrayList<Long> ar, ArrayList<Long>nums){ long f= (long)Math.sqrt(num); for (long i = 2; i <=f+1 ; i++) { if(num%i==0){ ar.add(i); long w=0; while(num%i==0){ w++; num=num/i; } nums.add(w); } } if(num!=1){ ar.add(num); nums.add((long)1); } } static long modExp(long a, long b, long mod) { //System.out.println("a is " + a + " and b is " + b); if (a==1) return 1; long ans = 1; while (b!=0) { if (b%2==1) { ans = (ans*a)%mod; } a = (a*a)%mod; b/=2; } return ans; } public static long modmul(long a, long b, long mod) { return b == 0 ? 0 : ((modmul(a, b >> 1, mod) << 1) % mod + a * (b & 1)) % mod; } static long sum(long n){ // System.out.println("lol="+ (n*(n-1))/2); return (n*(n+1))/2; } public static ArrayList<Integer> Sieve(int n) { boolean arr[]= new boolean [n+1]; Arrays.fill(arr,true); arr[0]=false; arr[1]=false; for (int i = 2; i*i <=n ; i++) { if(arr[i]){ for (int j = 2; j <=n/i ; j++) { int u= i*j; arr[u]=false; }} } ArrayList<Integer> ans= new ArrayList<>(); for (int i = 0; i <n+1 ; i++) { if(arr[i]){ ans.add(i); } } return ans; } static long power( long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static long ceil_div(long a, long b){ return (a+b-1)/b; } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a*b)/gcd(a, b); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
bececc9a4937cbe4a862802793d1664e
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.*; import java.util.*; public class Main extends PrintWriter { ArrayDeque<Integer>[] adj; int[][] edges; boolean[] done; int[] p; int dfs1(int u, int p) { done[u] = true; for(int e : adj[u]) { int v = edges[e][0] == u?edges[e][1]:edges[e][0]; if(v == p) continue; if(!done[v]) { int c = dfs1(v, u); if(c >= 0) { cycle[e] = true; if(c == u) return -2; else return c; } else if(c == -2) return c; } else { cycle[e] = true; return v; } } return -1; } void dfs2(int u, int p) { done[u] = true; comp[u] = comp_cnt; for(int e : adj[u]) { int v = edges[e][0] == u?edges[e][1]:edges[e][0]; if(v == p) continue; if(cycle[e]) continue; dfs2(v, u); } } int[] comp; int comp_cnt; boolean[] cycle; private void solve() { int t = sc.nextInt(); for(int tt = 1; tt <= t; tt++) { int n = sc.nextInt(); adj = new ArrayDeque[n]; edges = new int[n][]; for(int i = 0; i < n; i++) adj[i] = new ArrayDeque<>(); for(int i = 0; i < n; i++) { int u = sc.nextInt()-1; int v = sc.nextInt()-1; edges[i] = new int[] {u,v}; adj[u].add(i); adj[v].add(i); } done = new boolean[n]; cycle = new boolean[n]; dfs1(0, -1); comp = new int[n]; comp_cnt = 0; Arrays.fill(done, false); for(int u = 0; u < n; u++) { if(!done[u]) { dfs2(u, -1); comp_cnt++; } } long[] comp_sz = new long[comp_cnt]; for(int u = 0; u < n; u++) { comp_sz[comp[u]]++; } long ans = 0L; for(int i = 0; i < comp_cnt; i++) { ans += (comp_sz[i]*(comp_sz[i]-1))/2L; } long[] sum = new long[comp_cnt]; long total = 0L; for(int i = comp_cnt-1; i >= 0; i--) { total += comp_sz[i]; sum[i] = total; } for(int i = 0; i < comp_cnt-1; i++) { ans += 2L*comp_sz[i] * (sum[i+1]); } println(ans); } } // Main() throws FileNotFoundException { super(new File("output.txt")); } // InputReader sc = new InputReader(new FileInputStream("test_input.txt")); Main() { super(System.out); } InputReader sc = new InputReader(System.in); static class InputReader { InputReader(InputStream in) { this.in = in; } InputStream in; private byte[] buf = new byte[16384]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void main(String[] $) { new Thread(null, new Runnable() { public void run() { long start = System.nanoTime(); try {Main solution = new Main(); solution.solve(); solution.close();} catch (Exception e) {e.printStackTrace(); System.exit(1);} System.err.println((System.nanoTime()-start)/1E9); } }, "1", 1 << 27).start(); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
16397fe85f09495bbe5acf2871bfd6e4
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author revanth */ 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); ENumberOfSimplePaths solver = new ENumberOfSimplePaths(); solver.solve(1, in, out); out.close(); } static class ENumberOfSimplePaths { ArrayList<Integer>[] adj; int[] clr; int[] par; long[] size; HashSet<Integer> hs; boolean detect(int s) { clr[s] = 1; for (int c : adj[s]) { if (c == par[s]) continue; if (clr[c] == 1) { hs.add(s); int x = par[s]; while (x != c) { hs.add(x); x = par[x]; } hs.add(x); return true; } par[c] = s; if (detect(c)) return true; } clr[s] = 2; return false; } void dfs(int s, int p) { size[s] = 1; for (int c : adj[s]) { if (c == p || hs.contains(c)) continue; dfs(c, s); size[s] += size[c]; } } public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); clr = new int[n + 1]; par = new int[n + 1]; size = new long[n + 1]; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); adj[x].add(y); adj[y].add(x); } hs = new HashSet<>(); par[1] = 0; detect(1); for (int k : hs) dfs(k, 0); long ans = 0; for (int k : hs) ans += ((size[k] * (size[k] - 1)) / 2 + size[k] * (n - size[k])); out.println(ans); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int snumChars; private InputReader.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 { boolean isSpaceChar(int ch); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
bace5b5295e2e5c4cb7420c350e03faf
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { static Vector<Vector<Integer>>e; public static void main(String[] args) { Read cin = new Read(System.in); int T = cin.nextInt(); while(T>0){ T-=1; int n =cin.nextInt(); boolean[] vis = new boolean[n+5]; long[] siz = new long[n+5]; int[] deg = new int[n+5]; e = new Vector<>(); for(int i=0;i<=n;i++){ Vector<Integer>tmp = new Vector<Integer>(); e.add(tmp); } for(int i=1;i<=n;i++){ int u = cin.nextInt(); int v = cin.nextInt(); deg[v]++; deg[u]++; e.get(u).add(v); e.get(v).add(u); } Queue<Integer> q = new LinkedList<>(); for(int i=1;i<=n;i++){ siz[i] = 1; vis[i] = false; if(deg[i] == 1){ vis[i] = true; q.add(i); } } while(q.size()>0){ int u = q.peek(); q.poll(); for(int i=0;i<e.get(u).size();i++){ int v = e.get(u).get(i); if(vis[v] == true) continue; siz[v]+=siz[u]; deg[v]--; if(deg[v] == 1){ vis[v] = true; q.add(v); } } } long ans = 0; for(int i=1;i<=n;i++){ if(vis[i] == false){ ans+=siz[i]*(siz[i]-1)/2; ans+=siz[i]*(n-siz[i]); } } System.out.println(ans); } } } class Read {//自定义快读 Read public BufferedReader reader; public StringTokenizer tokenizer; public Read(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 String nextLine() { String str = null; try { str = reader.readLine(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return str; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
c18804b6fe02e6fa0fb9060089142d72
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class simplePaths { public static void main(String[] args) { FastScanner scan=new FastScanner(); PrintWriter out=new PrintWriter(System.out); /* if it were a tree, the answer would be n(n-1)/2 so we take the mst, and then we add in all the paths that contain that extra edge not in the mst! the question is how do we find the number of paths containing that edge there is gonna be exactly 1 cycle in this graph if two nodes are on the "same side" of the cycle and outside the cycle, we can't connect a path with the extra edge. else we can! upd: the dfs is taking up all my time haha but we don't actually need to know what the cycle is we can just remove the outermost ones til we get to the cycle so degree 1 nodes are gone:) actually we dont need to do the mst either! */ int t=scan.nextInt(); for(int tt=0;tt<t;tt++) { int n=scan.nextInt(); a=new ArrayList[n]; for(int i=0;i<n;i++) a[i]=new ArrayList<>(); int[] deg=new int[n]; for(int i=0;i<n;i++) { int u=scan.nextInt()-1, v=scan.nextInt()-1; a[u].add(v); a[v].add(u); deg[u]++; deg[v]++; } long res=(long)n*(n-1); ArrayDeque<Integer> q=new ArrayDeque<>(); int[] endingvals=new int[n]; for(int i=0;i<n;i++) { if(deg[i]==1) { q.offer(i); endingvals[i]=1; } } //when we finish, endingvals[i] is positive iff i is part of the cycle //it represents how many nodes come off of it int[] parent=new int[n]; Arrays.fill(parent,-1); while(!q.isEmpty()) { int cur=q.poll(); boolean pushed=false; for(int nxt:a[cur]) { if(parent[nxt]==cur) continue; parent[cur]=nxt; deg[nxt]--; if(deg[nxt]==1) { q.offer(nxt); } if(endingvals[nxt]==0) endingvals[nxt]++; endingvals[nxt]+=endingvals[cur]; pushed=true; } if(pushed) endingvals[cur]=0; } for(int i=0;i<n;i++) { res-=(long)endingvals[i]*(endingvals[i]-1)/2; } out.println(res); } out.close(); } static ArrayList<Integer>[] a; static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
2fd5f9bbaf272b8bf89518d24124da27
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class simplePaths { public static void main(String[] args) { FastScanner scan=new FastScanner(); PrintWriter out=new PrintWriter(System.out); /* if it were a tree, the answer would be n(n-1)/2 so we take the mst, and then we add in all the paths that contain that extra edge not in the mst! the question is how do we find the number of paths containing that edge there is gonna be exactly 1 cycle in this graph if two nodes are on the "same side" of the cycle and outside the cycle, we can't connect a path with the extra edge. else we can! upd: the dfs is taking up all my time haha but we don't actually need to know what the cycle is we can just remove the outermost ones til we get to the cycle so degree 1 nodes are gone:) actually we dont need to do the mst either! */ int t=scan.nextInt(); for(int tt=0;tt<t;tt++) { int n=scan.nextInt(); a=new ArrayList[n]; for(int i=0;i<n;i++) a[i]=new ArrayList<>(); int[] deg=new int[n]; // int eu=-1, ev=-1; // DSU d=new DSU(n); for(int i=0;i<n;i++) { int u=scan.nextInt()-1, v=scan.nextInt()-1; a[u].add(v); a[v].add(u); // if(d.unite(u,v)) { // //already united so this is the extra edge // eu=u; // ev=v; // } deg[u]++; deg[v]++; } long res=(long)n*(n-1); ArrayDeque<Integer> q=new ArrayDeque<>(); int[] endingvals=new int[n]; for(int i=0;i<n;i++) { if(deg[i]==1) { q.offer(i); endingvals[i]=1; } } //when we finish, endingvals[i] is positive iff i is part of the cycle //it represents how many nodes come off of it int[] parent=new int[n]; Arrays.fill(parent,-1); while(!q.isEmpty()) { int cur=q.poll(); // System.out.println("processing "+(cur+1)); boolean pushed=false; for(int nxt:a[cur]) { if(parent[nxt]==cur) continue; parent[cur]=nxt; // System.out.println("nxt "+(nxt+1)); deg[nxt]--; if(deg[nxt]==1) { q.offer(nxt); } if(endingvals[nxt]==0) endingvals[nxt]++; endingvals[nxt]+=endingvals[cur]; // System.out.println(endingvals[nxt]); pushed=true; } if(pushed) endingvals[cur]=0; } for(int i=0;i<n;i++) { res-=(long)endingvals[i]*(endingvals[i]-1)/2; } // System.out.println(Arrays.toString(endingvals)); out.println(res); } out.close(); } static ArrayList<Integer>[] a; // public static boolean dfs(int start, int at, int prev, boolean[] cycle) { // boolean res=false; // for(int nxt:a[at]) { // if(nxt==prev) continue; // if(nxt==start) return true; // res|=dfs(start,nxt,at,cycle); // } // return cycle[at]=res; // } // public static long bfs(int start, boolean[] dont) { // ArrayDeque<Integer> q=new ArrayDeque<>(); // boolean[] v=new boolean[a.length]; // q.offer(start); // v[start]=true; // int ct=0; // // while(!q.isEmpty()) { // int cur=q.poll(); // ct++; // for(int nxt:a[cur]) { // if(v[nxt]||dont[nxt]) continue; // v[nxt]=true; // q.offer(nxt); // } // } // return ct; // // } // static class DSU { // int n; // int[] parent, size; // // public DSU(int v) { // n = v; // parent = new int[n]; // size = new int[n]; // for(int i = 0; i < n; i++) { // parent[i] = i; // size[i] = 1; // } // } // // public int findRoot(int curr) { // if(curr == parent[curr]) return curr; // return parent[curr] = findRoot(parent[curr]); // } // // public boolean unite(int a, int b) { // int rootA = findRoot(a); // int rootB = findRoot(b); // if(rootA == rootB) return true; // if(size[rootA] > size[rootB]) { // parent[rootB] = rootA; // size[rootA] += size[rootB]; // } // else { // parent[rootA] = rootB; // size[rootB] += size[rootA]; // } // return false; // } // // } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output
PASSED
52b531b5712272a9f184f8aaa7ec102a
train_000.jsonl
1606228500
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; /* 1 3 1 2 2 3 1 3 1 4 1 2 2 3 3 4 4 2 */ public class E { public static void main(String[] args) { FastScanner fs=new FastScanner(); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(); Node[] nodes=new Node[n]; for (int i=0; i<n; i++) nodes[i]=new Node(i); for (int i=0; i<n; i++) { int a=fs.nextInt()-1, b=fs.nextInt()-1; nodes[a].adj.add(nodes[b]); nodes[b].adj.add(nodes[a]); } nodes[0].dfs(null, new ArrayDeque<>()); DisjointSet dj=new DisjointSet(n); long nPaths=n*(long)(n-1)/2*2; for (Node nn:nodes) for (Node adj:nn.adj) if (!adj.inCycle) dj.union(nn.id, adj.id); boolean[] processed=new boolean[n]; for (int i=0; i<n; i++) { int at=dj.find(i); if (processed[at]) continue; processed[at]=true; // System.out.println("Processing "+at+" "+dj.size[at]+" "+nodes[i].inCycle); nPaths-=dj.size[at]*(long)(dj.size[at]-1)/2; } System.out.println(nPaths); } } static class Node { ArrayList<Node> adj=new ArrayList<>(); boolean inCycle=false; boolean visited=false; Node par; int subtreeSize, id; public Node(int id) { this.id=id; } public void dfs(Node from, ArrayDeque<Node> stk) { // System.out.println("DFSing in "+id+" "+from); if (visited) { if (inCycle) return; //pop from cycle while (true) { Node next=stk.removeLast(); next.inCycle=true; // System.out.println("Marking "+next+" as being in a cycle"); if (next==this) { break; } } return; } visited=true; stk.addLast(this); for (Node nn:adj) if (nn!=from) nn.dfs(this, stk); if (!stk.isEmpty()) stk.removeLast(); } public String toString() { return ""+id; } } static class DisjointSet { int[] s; int[] size; public DisjointSet(int n) { Arrays.fill(s = new int[n], -1); size=new int[n]; Arrays.fill(size, 1); } public int find(int i) { return s[i] < 0 ? i : (s[i] = find(s[i])); } public boolean union(int a, int b) { if ((a = find(a)) == (b = find(b))) return false; if(s[a] == s[b]) s[a]--; if(s[a] <= s[b]) { s[b] = a; size[a]+=size[b]; } else { s[a] = b; size[b]+=size[a]; } return true; } } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
2 seconds
["6\n11\n18"]
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
Java 8
standard input
[ "combinatorics", "dfs and similar", "trees", "graphs" ]
1277cf54097813377bf37be445c06e7e
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
null
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
standard output