exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
eeea0ea350d063fed4edc21cdc300434
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; public class lexo { static class limit{ int l,r; limit(){ this.l=-1; this.r=-1; } } public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String s[]=br.readLine().split(" "); int f[]=new int[n]; limit l[]=new limit[n]; int c[]=new int[n]; int cf[]=new int[n]; int i,a; for( i=0;i<n;i++) { a=Integer.parseInt(s[i]); a--; c[i]=a; if(f[a]==0) { l[a]=new limit(); } f[a]++; if(l[a].l==-1) { l[a].l=i; } l[a].r=i; } int dp[]=new int[n+1]; for(i=n-1;i>=0;i--) { dp[i]=dp[i+1]; cf[c[i]]++; if(i==l[c[i]].l) { dp[i]=Math.max(dp[i],f[c[i]]+dp[l[c[i]].r +1]); } else { dp[i]=Math.max(dp[i], cf[c[i]]); } } System.out.println(n-dp[0]); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
e710916e8a6ddeb0d8e00346cb6d441d
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.StringTokenizer; public class COVID { static long mod = 998244353 ; static PrintWriter pw; static ArrayList<Integer>[] adjList; static int INF=(int)1e8; static double EPS=1e-9; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t=1; test: while(t-->0) { int n=sc.nextInt(); int[] arr=sc.nextIntArr(n); Integer[] l=new Integer[n+1]; Integer[] r=new Integer[n+1]; int[] cnt=new int[n+1]; int[] dp=new int[n+1]; for(int i=0;i<arr.length;i++) { if(l[arr[i]]==null)l[arr[i]]=i; r[arr[i]]=i; // cnt[arr[i]]++; } for(int i=n-1;i>=0;i--) { dp[i]=dp[i+1]; cnt[arr[i]]++; if(i==l[arr[i]]) dp[i]=Math.max(dp[i], dp[r[arr[i]]+1]+cnt[arr[i]]); else dp[i]=Math.max(dp[i], cnt[arr[i]]); } // System.out.println(Arrays.toString(dp)); pw.println(n-dp[0]); } pw.flush(); } public static long gcd(long a, long b) { if(b==0)return a; return gcd(b,a%b); } static long pow(long p, long e) { long ans = 1; while (e > 0) { if ((e & 1) == 1) ans = ((ans * 1l * p)); e >>= 1; { } p = ((p * 1l * p)); } return ans; } static long powmod(long b, long e, int mod) { long ans = 1; b %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * b) % mod); e >>= 1; b = (int) ((b * 1l * b) % mod); } return ans; } public static long add(long a, long b) { return (a + b) % mod; } public static long sub(long a, long b) { return (a - b + mod) % mod; } public static long mul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static class longPair implements Comparable<longPair> { long x, y; public longPair(long a, long b) { x = a; y = b; } public int compareTo(longPair p) { return (p.x == x) ? ((p.y == y) ? 0 : (y > p.y) ? 1 : -1) : (x > p.x) ? 1 : -1; } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int a, int b) { this.x = a; y = b; } public int compareTo(Pair o) { return (x == o.x) ? ((y > o.y) ? 1 : (y == o.y) ? 0 : -1) : ((x > o.x) ? 1 : -1); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } 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 long[] nextLongArr(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } 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; } if (sb.length() == 18) { res += Long.parseLong(sb.toString()) / f; sb = new StringBuilder("0"); } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } public static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
2362c13ca282ee3248579fe2121faf8b
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.StringTokenizer; public class COVID { static long mod = 998244353 ; static PrintWriter pw; static ArrayList<Integer>[] adjList; static int INF=(int)1e8; static double EPS=1e-9; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t=1; test: while(t-->0) { int n=sc.nextInt(); int[] arr=sc.nextIntArr(n); Integer[] l=new Integer[n+1]; Integer[] r=new Integer[n+1]; int[] cnt=new int[n+1]; int[] dp=new int[n+1]; for(int i=0;i<arr.length;i++) { if(l[arr[i]]==null)l[arr[i]]=i; r[arr[i]]=i; cnt[arr[i]]++; } int sum=0; int tot=0;// longest subsequence with all colors have the same occurence as the original array int[] c=new int[n+1]; int[] v=new int[n+1]; for(int i=1;i<=n;i++) { sum=Math.max(sum, tot+cnt[arr[i-1]]-c[arr[i-1]]);// the case where the last color has no of occ != original arr if(c[arr[i-1]]==0) { v[arr[i-1]]=tot+1; }else { v[arr[i-1]]++; } c[arr[i-1]]++; if(c[arr[i-1]]==cnt[arr[i-1]]) { tot=Math.max(tot, v[arr[i-1]]); } sum=Math.max(sum,tot); } pw.println(n-sum); // for(int i=n-1;i>=0;i--) { // dp[i]=dp[i+1]; // cnt[arr[i]]++; // if(i==l[arr[i]]) // dp[i]=Math.max(dp[i], dp[r[arr[i]]+1]+cnt[arr[i]]); // else // dp[i]=Math.max(dp[i], dp[r[arr[i]]+1]+cnt[arr[i]]); // } // System.out.println(Arrays.toString(dp)); // pw.println(n-dp[0]); } pw.flush(); } public static long gcd(long a, long b) { if(b==0)return a; return gcd(b,a%b); } static long pow(long p, long e) { long ans = 1; while (e > 0) { if ((e & 1) == 1) ans = ((ans * 1l * p)); e >>= 1; { } p = ((p * 1l * p)); } return ans; } static long powmod(long b, long e, int mod) { long ans = 1; b %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * b) % mod); e >>= 1; b = (int) ((b * 1l * b) % mod); } return ans; } public static long add(long a, long b) { return (a + b) % mod; } public static long sub(long a, long b) { return (a - b + mod) % mod; } public static long mul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static class longPair implements Comparable<longPair> { long x, y; public longPair(long a, long b) { x = a; y = b; } public int compareTo(longPair p) { return (p.x == x) ? ((p.y == y) ? 0 : (y > p.y) ? 1 : -1) : (x > p.x) ? 1 : -1; } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int a, int b) { this.x = a; y = b; } public int compareTo(Pair o) { return (x == o.x) ? ((y > o.y) ? 1 : (y == o.y) ? 0 : -1) : ((x > o.x) ? 1 : -1); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } 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 long[] nextLongArr(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } 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; } if (sb.length() == 18) { res += Long.parseLong(sb.toString()) / f; sb = new StringBuilder("0"); } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } public static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
7718f8b9a18fc6a54bc2e67c2883261f
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ESortingBooks solver = new ESortingBooks(); solver.solve(1, in, out); out.close(); } static class ESortingBooks { int n; int[] arr; int[] last; int[] first; int[] suffix; int[] count; int[] memo; public void readInput(Scanner sc) { n = sc.nextInt(); arr = new int[n]; last = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt() - 1; last[arr[i]] = i; } suffix = new int[n]; count = new int[n]; first = new int[n]; for (int i = n - 1; i >= 0; i--) { count[arr[i]]++; suffix[i] = Math.max(suffix[i], count[arr[i]]); first[arr[i]] = i; } } public void solve(int testNumber, Scanner sc, PrintWriter pw) { readInput(sc); int max = 0; memo = new int[n]; Arrays.fill(memo, -1); for (int i = 0; i < n; i++) { if (first[arr[i]] == i) max = Math.max(max, dp(i)); } pw.println(n - max); } private int dp(int idx) { if (idx == n) return 0; if (memo[idx] != -1) return memo[idx]; int max = dp(idx + 1); int maxSuffix = suffix[idx]; int takeCur = first[arr[idx]] == idx ? count[arr[idx]] + dp(last[arr[idx]] + 1) : -(int) 1e9; return memo[idx] = Math.max(max, Math.max(maxSuffix, takeCur)); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
b9c4a15f3ad81fa5b857f00bd41a675c
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ESortingBooks solver = new ESortingBooks(); solver.solve(1, in, out); out.close(); } static class ESortingBooks { int n; int[] arr; int[] last; int[] first; int[] suffix; int[] count; ArrayList<Integer>[] adjL; int[] memo; public void readInput(Scanner sc) { n = sc.nextInt(); arr = new int[n]; last = new int[n]; adjL = new ArrayList[n]; for (int i = 0; i < n; i++) adjL[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { arr[i] = sc.nextInt() - 1; last[arr[i]] = i; adjL[arr[i]].add(i); } suffix = new int[n]; count = new int[n]; first = new int[n]; for (int i = n - 1; i >= 0; i--) { count[arr[i]]++; suffix[i] = Math.max(suffix[i], count[arr[i]]); first[arr[i]] = i; } } public void solve(int testNumber, Scanner sc, PrintWriter pw) { readInput(sc); int max = 0; memo = new int[n]; Arrays.fill(memo, -1); for (int i = 0; i < n; i++) { if (first[arr[i]] == i) max = Math.max(max, dp(i)); } pw.println(n - max); } private int dp(int idx) { if (idx == n) return 0; if (memo[idx] != -1) return memo[idx]; int max = dp(idx + 1); int maxSuffix = suffix[idx]; int takeCur = first[arr[idx]] == idx ? count[arr[idx]] + dp(last[arr[idx]] + 1) : -(int) 1e9; return memo[idx] = Math.max(max, Math.max(maxSuffix, takeCur)); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
73074269ca57ab44626075bf8c6d04ab
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ESortingBooks solver = new ESortingBooks(); solver.solve(1, in, out); out.close(); } static class ESortingBooks { int n; int[] arr; int[] last; int[] first; int[] suffix; ArrayList<Integer>[] adjL; int[] memo; public void readInput(Scanner sc) { n = sc.nextInt(); arr = new int[n]; last = new int[n]; adjL = new ArrayList[n]; for (int i = 0; i < n; i++) adjL[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { arr[i] = sc.nextInt() - 1; last[arr[i]] = i; adjL[arr[i]].add(i); } suffix = new int[n]; int[] count = new int[n]; first = new int[n]; for (int i = n - 1; i >= 0; i--) { count[arr[i]]++; suffix[i] = Math.max(suffix[i], count[arr[i]]); first[arr[i]] = i; } } public void solve(int testNumber, Scanner sc, PrintWriter pw) { readInput(sc); int max = 0; memo = new int[n]; Arrays.fill(memo, -1); for (int i = 0; i < n; i++) { if (first[arr[i]] == i) max = Math.max(max, dp(i)); } pw.println(n - max); } private int dp(int idx) { if (idx == n) return 0; if (memo[idx] != -1) return memo[idx]; int max = dp(idx + 1); int maxSuffix = suffix[idx]; int takeCur = first[arr[idx]] == idx ? bs(idx) + dp(last[arr[idx]] + 1) : -(int) 1e9; return memo[idx] = Math.max(max, Math.max(maxSuffix, takeCur)); } private int bs(int idx) { int low = 0, high = adjL[arr[idx]].size() - 1; int ans = 0; while (low <= high) { int mid = (low + high) / 2; if (adjL[arr[idx]].get(mid) == idx) { return adjL[arr[idx]].size() - mid; } else if (adjL[arr[idx]].get(mid) < idx) { low = mid + 1; } else high = mid - 1; } return -1; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
699d27b9c20f76e230ff62e640186833
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; public class D { static class pair implements Comparable<pair> { int f; int s; double th; int id; public pair() { } public pair(int a, int b, int c) { f = a; s = b; th = (f * 1.00000) / (s * 1.00000); id = c; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub if (this.th > o.th) return -1; if (this.th == o.th) { return this.s - o.s; } else return 1; } } static int mod = (int) 1e9 + 7; static int ar[]; static Scanner sc = new Scanner(System.in); static StringBuilder out = new StringBuilder(); static ArrayList<Integer> grEven[]; static ArrayList<Integer> grOdd[]; static void sort(int a[], int n) { ArrayList<Integer> al = new ArrayList<>(); for (int i = 0; i < n; i++) { al.add(a[i]); } Collections.sort(al); for (int i = 0; i < n; i++) { a[i] = al.get(i); } } static void in(int a[], int n) throws IOException { for (int i = 0; i < n; i++) a[i] = sc.nextInt(); } public static void main(String[] args) throws IOException { int t =1;// sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); int ar[]=new int[n]; int freq[]=new int[n+1]; int occurIdx[][]=new int[n+1][2]; for(int [] a:occurIdx)Arrays.fill(a, -1); for(int i=0;i<n;i++) { ar[i]=sc.nextInt(); freq[ar[i]]++; if(occurIdx[ar[i]][0]==-1) { occurIdx[ar[i]][0]=i; occurIdx[ar[i]][1]=i; } else occurIdx[ar[i]][1]=i; } int dp[]=new int[n+1]; int []freqTillNow=new int[n+1]; for(int i=n-1;i>=0;i--) { freqTillNow[ar[i]]++; if(occurIdx[ar[i]][0]==i) { dp[i]=dp[occurIdx[ar[i]][1]+1]+freq[ar[i]]; } else { dp[i]=freqTillNow[ar[i]]; } dp[i]=Math.max(dp[i], dp[i+1]); } System.out.println(n-dp[0]); } System.out.println(out); } // static Reader sc=new Reader(); static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
8e5e1adab59a0cca952ffeec70fe7923
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; public class CF1481E extends PrintWriter { CF1481E() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1481E o = new CF1481E(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); int[] aa = new int[n]; int[] kk = new int[n]; int[] ll = new int[n]; int[] rr = new int[n]; for (int i = 0; i < n; i++) { int a = sc.nextInt() - 1; aa[i] = a; if (kk[a]++ == 0) ll[a] = i; rr[a] = i; } int[] bb = new int[n]; Arrays.fill(bb, -1); for (int a = 0; a < n; a++) if (kk[a] != 0) bb[rr[a]] = a; int[] qq = new int[n]; int[] dq = new int[n + 1]; for (int i = n - 1; i >= 0; i--) dq[i] = Math.max(dq[i], ++qq[aa[i]]); int ans = n; int[] dp = new int[n + 1]; for (int i = 1; i <= n; i++) { dp[i] = dp[i - 1]; int a = bb[i - 1]; if (a != -1) dp[i] = Math.max(dp[i], dp[ll[a]] + kk[a]); ans = Math.min(ans, n - dp[i] - dq[i]); } println(ans); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
460b652075096996aaa82c3ccb723efb
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import static java.lang.Math.*; public class E { public Object solve () { int N = sc.nextInt(); int [] A = dec(sc.nextInts()); int [][] P = new int [N][]; for (int i : rep(N)) { int a = A[i]; if (P[a] == null) P[a] = new int [] { i, i, 0 }; P[a][1] = i+1; ++P[a][2]; } int [][] L = new int [N+1][]; for (int a : rep(N)) if (P[a] != null) { int i = P[a][0], j = P[a][1], c = P[a][2]; L[j] = new int [] { i, c }; } int [] F = new int [N+1]; for (int j : req(1, N)) if (L[j] != null) { int i = L[j][0], c = L[j][1]; F[j] = max(F[j-1], F[i] + c); } else F[j] = F[j-1]; int [] G = new int [N], H = new int [N+1]; for (int i : sep(N)) H[i] = max(H[i+1], ++G[A[i]]); int res = 0; for (int i : req(N)) res = max(res, F[i] + H[i]); res = N - res; return res; } private static final int CONTEST_TYPE = 1; private static void init () { } private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static int [] req (int N) { return req(0, N); } private static int [] req (int S, int T) { return rep(S, T+1); } private static int [] sep (int N) { return sep(0, N); } private static int [] sep (final int S, final int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[T-1-i] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(min(b.length(), delim.length())); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (final StringBuilder b, Object o, final String delim) { append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 2) err(res, '(', time(), ')'); if (res.length() > 0) pw.println(res); if (DEBUG == 1) { pw.flush(); System.out.flush(); } } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new E().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { init(); @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); IOUtils.run(N); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
74c8a93e1df38cf4baf86f153316ad78
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; import java.util.Stack; public class Main { private static final String NO = "No"; private static final String YES = "Yes"; InputStream is; PrintWriter out; String INPUT = ""; private static final long MOD = 998244353L; void solve() { int T = 1;//ni(); for (int i = 0; i < T; i++) solve(i); } int N; void solve(int p) { N = ni(); int a[] = na(N); int dp[] = new int[N + 1]; int max[] = new int[N + 1]; int min[] = new int[N + 1]; int freq[] = new int[N + 1]; Arrays.fill(min, N + 1); for (int i = 0; i < N; i++) { max[a[i]] = Math.max(i, max[a[i]]); min[a[i]] = Math.min(i, min[a[i]]); } for (int i = N - 1; i >= 0; i--) { freq[a[i]]++; dp[i] = dp[i + 1]; if (min[a[i]] == i) { dp[i] = Math.max(dp[i], dp[max[a[i]] + 1] + freq[a[i]]); } dp[i] = Math.max(dp[i], freq[a[i]]); } // tr(dp); out.println(N - dp[0]); } // a^b long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % MOD; } y = (y * y) % MOD; b /= 2; } return x % MOD; } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private char[] nc(int n) { char[] ret = new char[n]; for (int i = 0; i < n; i++) ret[i] = nc(); return ret; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n) { if (!(isSpaceChar(b))) buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private List<Integer> na2(int n) { List<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) a.add(ni()); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long[][] nl(int n, int m) { long[][] a = new long[n][]; for (int i = 0; i < n; i++) a[i] = nl(m); return a; } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
a846d4f343026aec8ace67a1c5be30c8
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jaynil */ 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); ESortingBooks solver = new ESortingBooks(); solver.solve(1, in, out); out.close(); } static class ESortingBooks { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int a[] = new int[n]; int dp[] = new int[n + 1]; int max[] = new int[n]; int min[] = new int[n]; int freq[] = new int[n]; Arrays.fill(min, n + 1); for (int i = 0; i < n; i++) { a[i] = in.nextInt() - 1; max[a[i]] = Math.max(i, max[a[i]]); min[a[i]] = Math.min(i, min[a[i]]); } for (int i = n - 1; i >= 0; i--) { freq[a[i]]++; dp[i] = dp[i + 1]; if (min[a[i]] == i) { dp[i] = Math.max(dp[i], dp[max[a[i]] + 1] + freq[a[i]]); } dp[i] = Math.max(dp[i], freq[a[i]]); } out.println(n - dp[0]); } } 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\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
67033a0f6122fe9e00aa890a618fbea4
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public final class E { public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int n = fs.nextInt(); final int[] arr = fs.nextIntArray(n); final int[] l = new int[(int) (5e5 + 5)]; final int[] r = new int[(int) (5e5 + 5)]; final int[] f = new int[(int) (5e5 + 5)]; final int[] suff = new int[n]; final int[] dp = new int[n]; Arrays.fill(l, -1); for (int i = 0; i < n; i++) { if (l[arr[i]] == -1) { l[arr[i]] = i; } r[arr[i]] = i; dp[i] = -1; } int max = 0; for (int i = n - 1; i >= 0; i--) { max = Math.max(max, ++f[arr[i]]); suff[i] = max; } System.out.println(n - dfs(arr, f, l, r, suff, 0, dp)); } private static int dfs(int[] arr, int[] f, int[] l, int[] r, int[] suff, int idx, int[] dp) { if (idx == arr.length) { return 0; } if (dp[idx] != -1) { return dp[idx]; } int res = dfs(arr, f, l, r, suff, idx + 1, dp); if (l[arr[idx]] == idx) { res = Math.max(res, f[arr[idx]] + dfs(arr, f, l, r, suff, r[arr[idx]] + 1, dp)); } else { res = Math.max(res, suff[idx] + dfs(arr, f, l, r, suff, arr.length, dp)); } return dp[idx] = res; } static final class Utils { public static void shuffleSort(int[] x) { shuffle(x); Arrays.sort(x); } public static void shuffleSort(long[] x) { shuffle(x); Arrays.sort(x); } public static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } public static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
3abc72f4b73e922ee994429b60c20d29
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; /** @author KhanhNguyenn */ public class D{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ public void solve(InputReader in, PrintWriter out) { int[] A= new int[505050]; int[] D= new int[505050]; int[] L= new int[505050]; int[] R= new int[505050]; int[] C= new int[505050]; int N= in.nextInt(); for(int i = 1; i <= N; i++) { A[i]=in.nextInt(); if(L[A[i]]==0) L[A[i]] = i; R[A[i]] = i; C[A[i]]++; } for(int i = 1; i <= N; i++) { if(i != R[A[i]]) D[i] = D[i - 1]; else D[i] = Math.max(D[i - 1], D[L[A[i]] - 1] + C[A[i]]); } int ans = D[N]; for(int i = 1; i <= N; i++) C[i] = 0; for(int i = N; i >= 1; i--) { C[A[i]]++; ans = Math.max(ans, D[i - 1] + C[A[i]]); } out.println(N-ans); } } static class Pair implements Comparable<Pair>{ public int x, y; public Pair(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (this.x > o.x){ return 1; } else if (this.x < o.x){ return -1; } else{ return Integer.compare(this.y, o.y); } } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
cd32a296c19b84e32df35547b5f1b63d
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; /** @author KhanhNguyenn */ public class D{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ public void solve(InputReader in, PrintWriter out) { int[] A= new int[505050]; int[] D= new int[505050]; int[] L= new int[505050]; int[] R= new int[505050]; int[] C= new int[505050]; int N= in.nextInt(); for(int i = 1; i <= N; i++) { A[i]=in.nextInt(); if(L[A[i]]==0) L[A[i]] = i; R[A[i]] = i; C[A[i]]++; } for(int i = 1; i <= N; i++) { if(i != R[A[i]]) D[i] = D[i - 1]; else D[i] = Math.max(D[i - 1], D[L[A[i]] - 1] + C[A[i]]); } int ans = D[N]; for(int i = 1; i <= N; i++) C[i] = 0; for(int i = N; i >= 1; i--) { C[A[i]]++; ans = Math.max(ans, D[i - 1] + C[A[i]]); } out.println(N-ans); } } static class Pair implements Comparable<Pair>{ public int x, y; public Pair(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (this.x > o.x){ return 1; } else if (this.x < o.x){ return -1; } else{ return Integer.compare(this.y, o.y); } } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
31a6a2d378e8ff03700191cbc4168514
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
//package round699; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class E { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ a[i]--; } int[] ls = new int[n]; int[] rs = new int[n]; int[] fs = new int[n]; Arrays.fill(ls, -1); Arrays.fill(rs, -1); for(int i = 0;i < n;i++){ if(ls[a[i]] == -1)ls[a[i]] = i; rs[a[i]] = i; fs[a[i]]++; } int[][] qs = new int[n][]; int p = 0; for(int i = 0;i < n;i++){ if(fs[i] > 0){ qs[p++] = new int[]{ls[i], rs[i], rs[i]-ls[i]+1-fs[i]}; } } qs = Arrays.copyOf(qs, p); Arrays.sort(qs, (x, y) -> x[1] - y[1]); long[] dp = new long[n+1]; Arrays.fill(dp, Long.MAX_VALUE / 2); dp[0] = 0; p = 0; for(int x = 1;x <= n;x++){ dp[x] = dp[x-1] + 1; while(p < qs.length && qs[p][1]+1 <= x){ dp[x] = Math.min(dp[x], dp[qs[p][0]] + qs[p][2]); p++; } } for(int x = 0;x <= n;x++){ dp[x] -= x; } int[][] b = makeBuckets(a, n); StarrySkyTreeL sst = new StarrySkyTreeL(dp); long ans = n; for(int i = 0;i < n;i++){ for(int pos : b[i]){ ans = Math.min(ans, sst.min(0, pos+1) + n-1); sst.add(0, pos+1, -1); } for(int pos : b[i]){ sst.add(0, pos+1, 1); } } out.println(ans); } public static int[][] makeBuckets(int[] a, int sup) { int n = a.length; int[][] bucket = new int[sup+1][]; int[] bp = new int[sup+1]; for(int i = 0;i < n;i++)bp[a[i]]++; for(int i = 0;i <= sup;i++)bucket[i] = new int[bp[i]]; for(int i = n-1;i >= 0;i--)bucket[a[i]][--bp[a[i]]] = i; return bucket; } public static class StarrySkyTreeL { public final int M, H, N, LH; public long[] mins; public long[] plus; public static final long I = Long.MAX_VALUE/4; // I+plus<long public StarrySkyTreeL(int n) { N = n; M = Integer.highestOneBit(Math.max(n-1, 1))<<2; H = M>>>1; LH = Integer.numberOfTrailingZeros(H); mins = new long[M]; plus = new long[H]; } public StarrySkyTreeL(long[] a) { this(a.length); for(int i = 0;i < N;i++){ mins[H+i] = a[i]; } Arrays.fill(mins, H+N, M, I); for(int i = H-1;i >= 1;i--)propagate(i); } private void push1(int cur) { if(plus[cur] == 0)return; int L = cur*2, R = L + 1; mins[L] += plus[cur]; mins[R] += plus[cur]; if(L < H){ plus[L] += plus[cur]; plus[R] += plus[cur]; } plus[cur] = 0; } private void propagate(int i) { mins[i] = Math.min(mins[2*i], mins[2*i+1]) + plus[i]; } private void add1(int cur, long v) { mins[cur] += v; if(cur < H){ plus[cur] += v; } } private void push(int l, int r) { for(int i = LH;i >= 1;i--) { if (l >>> i << i != l) push1(l >>> i); if (r >>> i << i != r) push1(r >>> i); } } public void add(int l, int r, long v) { if(l >= r)return; l += H; r += H; push(l, r); for(int ll = l, rr = r;ll < rr;ll>>>=1,rr>>>=1){ if((ll&1) == 1) add1(ll++, v); if((rr&1) == 1) add1(--rr, v); } for(int i = 1;i <= LH;i++){ if(l>>>i<<i != l)propagate(l>>>i); if(r>>>i<<i != r)propagate(r>>>i); } } public long min(int l, int r){ long min = I; if(l >= r)return min; l += H; r += H; push(l, r); for(;l < r;l>>>=1,r>>>=1){ if((l&1) == 1)min = Math.min(min, mins[l++]); if((r&1) == 1)min = Math.min(min, mins[--r]); } return min; } public int firstle(int l, long v) { if(l >= H)return -1; int cur = H+l; for(int i = 1, j = Integer.numberOfTrailingZeros(H)-1;i <= cur;j--){ push1(i); i = i*2|cur>>>j&1; } while(true){ push1(cur); if(mins[cur] <= v){ if(cur >= H)return cur-H; cur = 2*cur; }else{ cur++; if((cur&cur-1) == 0)return -1; cur = cur>>>Integer.numberOfTrailingZeros(cur); } } } public int lastle(int l, long v) { if(l < 0)return -1; int cur = H+l; for(int i = 1, j = Integer.numberOfTrailingZeros(H)-1;i <= cur;j--){ push1(i); i = i*2|cur>>>j&1; } while(true){ push1(cur); if(mins[cur] <= v){ if(cur >= H)return cur-H; cur = 2*cur+1; }else{ if((cur&cur-1) == 0)return -1; cur = cur>>>Integer.numberOfTrailingZeros(cur); cur--; } } } public long[] toArray() { return toArray(1, 0, H, new long[H]); } private long[] toArray(int cur, int l, int r, long[] ret) { if(r-l == 1){ ret[cur-H] = mins[cur]; }else{ toArray(2*cur, l, l+r>>>1, ret); toArray(2*cur+1, l+r>>>1, r, ret); for(int i = l;i < r;i++)ret[i] += plus[cur]; } return ret; } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
90c1a2ea1924cc860c88501692f38d60
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
// Don't place your source in a package import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner {//scanner from SecondThread BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int T=1; for(int t=0;t<T;t++){ int n=Int(); int A[]=new int[n]; for(int i=0;i<n;i++){ A[i]=Int(); } Solution sol=new Solution(); sol.solution(out,A); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ public void solution(PrintWriter out,int A[]){ //hint : find the maximum of unmove box, use n-max int n=A.length; reverse(A); int cnt[]=new int[n+100]; int dp[]=new int[n]; int l[]=new int[n+100];Arrays.fill(l,Integer.MAX_VALUE); int r[]=new int[n+100];Arrays.fill(r,Integer.MIN_VALUE); for(int i=0;i<A.length;i++){ l[A[i]]=Math.min(l[A[i]],i); r[A[i]]=Math.max(r[A[i]],i); } for(int i=0;i<A.length;i++){ if(i-1>=0)dp[i]=dp[i-1]; cnt[A[i]]++; if(i==r[A[i]]){ int left=l[A[i]]-1; dp[i]=Math.max(dp[i],cnt[A[i]]+get(dp,left)); } else{ dp[i]=Math.max(dp[i],cnt[A[i]]); } } out.println(n-dp[n-1]); } public int get(int A[],int i){ if(i<0)return 0; return A[i]; } public void reverse(int A[]){ List<Integer>list=new ArrayList<>(); for(int i:A)list.add(i); Collections.reverse(list); for(int i=0;i<A.length;i++)A[i]=list.get(i); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
984b80a6feb77a1f0f9a1a64598a858b
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 1e9 + 10; static final long OO = (long) 2e18 + 10; static final int MOD = (int) 1e9 + 7; static void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int[] l = new int[n + 1]; Arrays.fill(l, -1); int[] r = new int[n + 1]; Arrays.fill(r, -1); for (int i = 0; i < n; i++) { if (l[a[i]] == -1) l[a[i]] = i; r[a[i]] = i; } int[] dp = new int[n + 1]; int[] cnt = new int[n + 1]; for (int i = n - 1; i >= 0; i--) { dp[i] = dp[i + 1]; cnt[a[i]]++; if (i == l[a[i]]) dp[i] = Math.max(dp[i], cnt[a[i]] + dp[r[a[i]] + 1]); else dp[i] = Math.max(dp[i], cnt[a[i]]); } out.println(n - dp[0]); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int T = 1; // T = in.nextInt(); while (T-- > 0) solve(); out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
142161f5bcd85fdc56ff68b77b060a6c
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 1e9 + 10; static final long OO = (long) 2e18 + 10; static final int MOD = (int) 1e9 + 7; static void solve() { int n = in.nextInt(); int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } final int N = (int) 5e5 + 10; ArrayList<Integer>[] pos = new ArrayList[N]; Arrays.setAll(pos, i -> new ArrayList<>()); for (int i = 1; i <= n; i++) { pos[a[i]].add(i); } int max = 0; int[] dp = new int[n + 1]; for (int i = 1; i <= n; i++) { int c = a[i]; dp[i] = dp[i - 1]; if (i == pos[c].get(pos[c].size() - 1)) { for (int j = 0; j < pos[c].size(); j++) { max = Math.max(max, dp[pos[c].get(j) - 1] + pos[c].size() - j); } dp[i] = Math.max(dp[i], dp[pos[c].get(0) - 1] + pos[c].size()); } } out.println(n - max); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int T = 1; // T = in.nextInt(); while (T-- > 0) solve(); out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
dfa7ef7db267c8a0de7e1bc1446dbb43
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
//stan hu tao import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class x1481E { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = readArr(N, infile, st); int[] left = new int[N+1]; int[] right = new int[N+1]; Arrays.fill(left, -1); int[] freq = new int[N+1]; for(int i=0; i < N; i++) { freq[arr[i]]++; if(left[arr[i]] == -1) left[arr[i]] = i; right[arr[i]] = i; } int[] cnt = new int[N+1]; int[] dp = new int[N]; dp[N-1] = 1; cnt[arr[N-1]] = 1; for(int i=N-2; i >= 0; i--) { dp[i] = dp[i+1]; cnt[arr[i]]++; if(i == left[arr[i]]) { int val = freq[arr[i]]; if(right[arr[i]] < N-1) val += dp[right[arr[i]]+1]; dp[i] = max(dp[i], val); } else dp[i] = max(dp[i], cnt[arr[i]]); } System.out.println(N-dp[0]); } public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
e1a09f60b5c9a34664c18bc3950ad980
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { int n, m, k; static boolean use_n_tests = false; void solve(FastScanner in, PrintWriter out, int testNumber) { n = in.nextInt(); int[] a = in.nextArray(n); int[] f = new int[n + 1]; int[] l = new int[n + 1]; Arrays.fill(l, 1000000); int[] r = new int[n + 1]; for (int i = 0; i < n; i++) { f[a[i]]++; l[a[i]] = Math.min(l[a[i]], i + 1); r[a[i]] = Math.max(r[a[i]], i + 1); } int[] dp = new int[n + 1]; // max unmoved elements int[] cf = new int[n + 1]; for (int i = n - 1; i >= 0; i--) { int color = a[i]; dp[i] = dp[i + 1]; cf[color]++; if (i == l[color] - 1) { // stay all color at the place dp[i] = Math.max(f[color] + dp[r[color]], dp[i]); } else { dp[i] = Math.max(dp[i], cf[color]); } } out.println(n - dp[0]); } // ****************************** template code *********** static int stack_size = 1 << 27; void pre_solve() { } class Coeff { long mod; long[][] C; long[] fact; boolean cycleWay = false; Coeff(int n, long mod) { this.mod = mod; fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = i; fact[i] %= mod; fact[i] *= fact[i - 1]; fact[i] %= mod; } } Coeff(int n, int m, long mod) { // n > m cycleWay = true; this.mod = mod; C = new long[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, m); j++) { if (j == 0 || j == i) { C[i][j] = 1; } else { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; C[i][j] %= mod; } } } } public long C(int n, int m) { if (cycleWay) { return C[n][m]; } return fC(n, m); } private long fC(int n, int m) { return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod; } private long inv(long r) { if (r == 1) return 1; return ((mod - mod / r) * inv(mod % r)) % mod; } } class Pair { int first; int second; public int getFirst() { return first; } public int getSecond() { return second; } } class MultisetTree<T> { int size = 0; TreeMap<T, Integer> mp = new TreeMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } boolean contains(T x) { return mp.containsKey(x); } T greatest() { return mp.lastKey(); } T smallest() { return mp.firstKey(); } int size() { return size; } int diffSize() { return mp.size(); } void clear() { mp.clear(); size = 0; } } class Multiset<T> { int size = 0; Map<T, Integer> mp = new HashMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } boolean contains(T x) { return mp.containsKey(x); } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } int size() { return size; } int diffSize() { return mp.size(); } } static class Range { int l, r; int id; public int getL() { return l; } public int getR() { return r; } public Range(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } static class Array { static Range[] readRanges(int n, FastScanner in) { Range[] result = new Range[n]; for (int i = 0; i < n; i++) { result[i] = new Range(in.nextInt(), in.nextInt(), i); } return result; } static boolean isSorted(Integer[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static public <T> long sum(T[] a) { long sum = 0; for (T x : a) { if (x instanceof Integer) { sum += (Integer) x; } else { sum += (Long) x; } } return sum; } static public int min(Integer[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int min(int[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int max(Integer[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int max(int[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int[] readint(int n, FastScanner in) { int[] out = new int[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } } class Graph { List<List<Integer>> graph; Graph(int n) { create(n); } void create(int n) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } this.graph = graph; } void readBi(int m, FastScanner in) { for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; graph.get(v).add(u); graph.get(u).add(v); } } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String line() { String result = ""; try { result = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return result; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long[] nextArrayL(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Long[] nextArrayL2(int n) { Long[] res = new Long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Integer[] nextArray2(int n) { Integer[] res = new Integer[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long nextLong() { return Long.parseLong(next()); } } void run_t_tests() { pre_solve(); int t = in.nextInt(); int i = 0; while (t-- > 0) { solve(in, out, i++); } } void run_one() { solve(in, out, -1); } @Override public void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); if (use_n_tests) { run_t_tests(); } else { run_one(); } out.close(); } static FastScanner in; static PrintWriter out; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(null, new Main(), "", stack_size); thread.start(); thread.join(); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
19a7eed4ad74631e86d1dc49b926f42c
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; public class G { static pair[] bo; static int[] f; public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = sc.nextInt(); int a[] = sc.intArr(n); f = new int[n]; int[] r = new int[n]; int[] l = new int[n]; Arrays.fill(l, -1); for (int i = 0; i < l.length; i++) { if (l[a[i] - 1] == -1) l[a[i] - 1] = i; } Arrays.fill(r, -1); int[] dp = new int[n + 1]; for (int i = n - 1; i >= 0; i--) { if (r[a[i] - 1] == -1) { r[a[i] - 1] = i + 1; } f[a[i] - 1]++; if (l[a[i] - 1] == i) dp[i] = Math.min(1 + dp[i + 1], r[a[i] - 1] - l[a[i] - 1] - f[a[i] - 1] + dp[r[a[i] - 1]]); else dp[i] = Math.min(1 + dp[i + 1], n - i - f[a[i] - 1] ); } System.out.println(dp[0]); } pw.flush(); } /////////////////////////////////////////////////////////////////////////////////////////// static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static class pair implements Comparable<pair> { int x, y; boolean w, l; PriorityQueue<Long> pq; public pair(boolean a, boolean b) { w = a; l = b; } pair(int s, int d) { x = s; y = d; } @Override public int compareTo(pair p) { return Long.compare(x, p.x); } @Override public String toString() { return x + " " + y; } } static long mod(long ans, int mod) { return (ans % mod + mod) % mod; } 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); } public static int log(int n, int base) { int ans = 0; while (n + 1 > base) { ans++; n /= base; } return ans; } static long pow(long b, long e) { long ans = 1; while (e > 0) { if ((e & 1) == 1) ans = ((ans * 1l * b)); e >>= 1; { } b = ((b * 1l * b)); } return ans; } static long powmod(long r, long e, int mod) { long ans = 1; r %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * r) % mod); e >>= 1; r = (int) ((r * 1l * r) % mod); } return ans; } static int ceil(int a, int b) { int ans = a / b; return a % b == 0 ? ans : ans + 1; } static long ceil(long a, long b) { long ans = a / b; return a % b == 0 ? ans : ans + 1; } static HashMap<Integer, Integer> compress(int a[]) { TreeSet<Integer> ts = new TreeSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int x : a) ts.add(x); for (int x : ts) { hm.put(x, hm.size() + 1); } return hm; } // Returns nCr % p static int C[]; static int nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; if (C[r] != 0) return C[r]; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public int[] intArr(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } return a; } public long[] longArr(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = nextLong(); } return a; } 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(); } } public static void shuffle(int[] times2) { int n = times2.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = times2[i]; times2[i] = times2[r]; times2[r] = tmp; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
6b35b50abbeb337c1256b30805541067
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; public class G { static pair[] bo; static int[] f; public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = sc.nextInt(); int a[] = sc.intArr(n); f = new int[n]; int[] r = new int[n]; int[] l = new int[n]; Arrays.fill(l, -1); for (int i = 0; i < l.length; i++) { if (l[a[i] - 1] == -1) l[a[i] - 1] = i; } Arrays.fill(r, -1); int[] dp = new int[n + 1]; for (int i = n - 1; i >= 0; i--) { if (r[a[i] - 1] == -1) { r[a[i] - 1] = i + 1; } f[a[i] - 1]++; if (l[a[i] - 1] == i) dp[i] = Math.max(dp[i + 1], f[a[i] - 1] + dp[r[a[i] - 1]]); else dp[i] = Math.max(dp[i + 1], f[a[i] - 1]); } System.out.println(n - dp[0]); } pw.flush(); } /////////////////////////////////////////////////////////////////////////////////////////// static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static class pair implements Comparable<pair> { int x, y; boolean w, l; PriorityQueue<Long> pq; public pair(boolean a, boolean b) { w = a; l = b; } pair(int s, int d) { x = s; y = d; } @Override public int compareTo(pair p) { return Long.compare(x, p.x); } @Override public String toString() { return x + " " + y; } } static long mod(long ans, int mod) { return (ans % mod + mod) % mod; } 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); } public static int log(int n, int base) { int ans = 0; while (n + 1 > base) { ans++; n /= base; } return ans; } static long pow(long b, long e) { long ans = 1; while (e > 0) { if ((e & 1) == 1) ans = ((ans * 1l * b)); e >>= 1; { } b = ((b * 1l * b)); } return ans; } static long powmod(long r, long e, int mod) { long ans = 1; r %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * r) % mod); e >>= 1; r = (int) ((r * 1l * r) % mod); } return ans; } static int ceil(int a, int b) { int ans = a / b; return a % b == 0 ? ans : ans + 1; } static long ceil(long a, long b) { long ans = a / b; return a % b == 0 ? ans : ans + 1; } static HashMap<Integer, Integer> compress(int a[]) { TreeSet<Integer> ts = new TreeSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int x : a) ts.add(x); for (int x : ts) { hm.put(x, hm.size() + 1); } return hm; } // Returns nCr % p static int C[]; static int nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; if (C[r] != 0) return C[r]; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public int[] intArr(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } return a; } public long[] longArr(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = nextLong(); } return a; } 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(); } } public static void shuffle(int[] times2) { int n = times2.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = times2[i]; times2[i] = times2[r]; times2[r] = tmp; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
0c2371ffc12b032d4efedbeab01500fe
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
/** * author: derrick20 * created: 2/24/21 11:34 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class SortingBooks { static FastScanner sc = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int N = sc.nextInt(); int[] color = new int[N]; int[] freq = new int[N + 1]; for (int i = 0; i < N; i++) { int c = sc.nextInt(); color[i] = c; freq[c]++; } int ans = 0; int clusters = 0; int[] dp = new int[N + 1]; boolean[] vis = new boolean[N + 1]; for (int c : color) { ans = max(ans, clusters + freq[c]); if (!vis[c]) { vis[c] = true; // first one, give it the occurrences dp[c] = clusters + freq[c]; } freq[c]--; if (freq[c] == 0) { clusters = max(clusters, dp[c]); // last one, now we can consider it } } out.println(N - ans); out.close(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } int nextInt() { return (int) nextLong(); } long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } double nextDouble() { boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } double cur = nextLong(); if (c != '.') { return neg ? -cur : cur; } else { double frac = nextLong() / cnt; return neg ? -cur - frac : cur + frac; } } String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
239b2fe814ac9584521efe5a35aed804
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
/** * author: derrick20 * created: 2/24/21 11:34 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class SortingBooks { static FastScanner sc = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int N = sc.nextInt(); int[] color = new int[N + 1]; int[] total = new int[N + 1]; int[] freq = new int[N + 1]; int[] first = new int[N + 1]; for (int i = 1; i <= N; i++) { int c = sc.nextInt(); color[i] = c; freq[c]++; total[c]++; if (first[c] == 0) { first[c] = i; } } int ans = 0; int[] dp = new int[N + 1]; for (int i = 1; i <= N; i++) { int c = color[i]; dp[i] = dp[i - 1]; ans = max(ans, dp[i] + freq[c]); freq[c]--; if (freq[c] == 0) { dp[i] = max(dp[i], dp[first[c] - 1] + total[c]); } } // System.out.println(Arrays.toString(dp)); ans = max(ans, dp[N]); out.println(N - ans); out.close(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } int nextInt() { return (int) nextLong(); } long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } double nextDouble() { boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } double cur = nextLong(); if (c != '.') { return neg ? -cur : cur; } else { double frac = nextLong() / cnt; return neg ? -cur - frac : cur + frac; } } String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
fe0233976967434a3fba904d27786e5c
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.util.*; import java.io.*; public class EdA { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] omkar) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); // String input1 = bf.readLine().trim(); // String input2 = bf.readLine().trim(); // COMPARING INTEGER OBJECTS U DO DOT EQUALS NOT == int n = sc.nextInt(); int[] arr = readArrayInt1(n); int[] freqcount = new int[n+1]; int[] fulldp = new int[n+1]; int[] l = new int[n+1]; int[] r = new int[n+1]; Arrays.fill(l, -1); Arrays.fill(r, -1); for(int j = 1;j<=n;j++){ freqcount[arr[j]]++; if (l[arr[j]] == -1) l[arr[j]] = j; r[arr[j]] = j; } for(int j = 1;j<=n;j++){ if (r[arr[j]] != j){ fulldp[j] = fulldp[j-1]; } else{ fulldp[j] = Math.max(fulldp[j-1], fulldp[l[arr[j]]-1]+freqcount[arr[j]]); } } int suffix = 0; int ans = 0; Arrays.fill(freqcount, 0); for(int j = n;j>=1;j--){ freqcount[arr[j]]++; suffix = Math.max(suffix, freqcount[arr[j]]); ans = Math.max(ans, fulldp[j-1]+suffix); } out.println(n-ans); // for(int j = 0;j<array.length;j++){ // out.print(array[j] + " "); // } // out.println(); out.close(); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
36411aacf8dd089c83810ebaed7a4182
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.util.*; public class p1481E { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(),a[]=new int[n],freq[]=new int[n],c[]=new int[n],dp[]=new int[n+1],l[]=new int[n],r[]=new int[n]; Arrays.fill(l,-1); for(int i=0;i<n;i++) { freq[a[i]=sc.nextInt()-1]++; if(l[a[i]]<0) l[a[i]]=i; r[a[i]]=i; } for(int i=n-1;i>-1;i--) { c[a[i]]++; dp[i]=Math.max(c[a[i]], dp[i+1]); if(i==l[a[i]]) dp[i]=Math.max(dp[i],dp[r[a[i]]+1]+freq[a[i]]); } System.out.println(n-dp[0]); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
ea63909e75a6065bed73379317ccd55c
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.util.*; public class p1418E { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(),a[]=new int[n],freq[]=new int[n],c[]=new int[n],dp[]=new int[n+1]; Pair pos[]=new Pair[n]; Arrays.fill(pos, new Pair(-1,-1)); for(int i=0;i<n;i++) { freq[a[i]=sc.nextInt()-1]++; if(pos[a[i]].left==-1) pos[a[i]]=new Pair(i,i); pos[a[i]].right=i; } for(int i=n-1;i>-1;i--) { dp[i]=dp[i+1]; c[a[i]]++; if(i==pos[a[i]].left) dp[i]=Math.max(dp[i],dp[pos[a[i]].right+1]+freq[a[i]]); else dp[i] = Math.max(dp[i] ,c[a[i]]); } System.out.println(n-dp[0]); } static class Pair{ int left,right; Pair(int x,int y){left=x;right=y;} } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
328b583d671d7e80a2041aa8910c15c3
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); GMaximizeTheRemainingString solver = new GMaximizeTheRemainingString(); solver.solve(1, in, out); out.close(); } static class GMaximizeTheRemainingString { int[] a; int n; public void readInput(Scanner sc) { n = sc.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); } public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = 1; while (q-- > 0) { readInput(sc); int[] last = new int[n + 1]; int[] first = new int[n + 1]; Arrays.fill(first, -1); int[] cnt = new int[n + 1]; int[] cnt2 = new int[n + 1]; for (int i = 0; i < n; i++) { if (first[a[i]] == -1) first[a[i]] = i; last[a[i]] = i; cnt[a[i]]++; cnt2[a[i]]++; } int[] dp = new int[n]; int[] max = new int[n]; int ans = 0; for (int i = 0; i < n; i++) { int cur = cnt[a[i]]; if (i > 0) max[i] = max[i - 1]; ans = Math.max(ans, cur + max[i]); if (last[a[i]] == i) { dp[i] = cnt2[a[i]]; if (first[a[i]] != 0) dp[i] += max[first[a[i]] - 1]; } max[i] = Math.max(max[i], dp[i]); cnt[a[i]]--; } // System.out.println(Arrays.toString(max)); pw.println(n - ans); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
2534dc87b5edf8fd0abe79d6998561bd
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.*; public class G { static pair[] bo; static int[] f; public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = sc.nextInt(); int a[] = sc.intArr(n); f = new int[n]; int[] r = new int[n]; int[] l = new int[n]; Arrays.fill(l, -1); for (int i = 0; i < l.length; i++) { if (l[a[i] - 1] == -1) l[a[i] - 1] = i; } Arrays.fill(r, -1); int[] dp = new int[n + 1]; for (int i = n - 1; i >= 0; i--) { if (r[a[i] - 1] == -1) { r[a[i] - 1] = i + 1; } f[a[i] - 1]++; if (l[a[i] - 1] == i) dp[i] = Math.min(1 + dp[i + 1], r[a[i] - 1] - l[a[i] - 1] - f[a[i] - 1] + dp[r[a[i] - 1]]); else dp[i] = Math.min(1 + dp[i + 1], n - i - f[a[i] - 1] ); } System.out.println(dp[0]); } pw.flush(); } /////////////////////////////////////////////////////////////////////////////////////////// static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static class pair implements Comparable<pair> { int x, y; boolean w, l; PriorityQueue<Long> pq; public pair(boolean a, boolean b) { w = a; l = b; } pair(int s, int d) { x = s; y = d; } @Override public int compareTo(pair p) { return Long.compare(x, p.x); } @Override public String toString() { return x + " " + y; } } static long mod(long ans, int mod) { return (ans % mod + mod) % mod; } 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); } public static int log(int n, int base) { int ans = 0; while (n + 1 > base) { ans++; n /= base; } return ans; } static long pow(long b, long e) { long ans = 1; while (e > 0) { if ((e & 1) == 1) ans = ((ans * 1l * b)); e >>= 1; { } b = ((b * 1l * b)); } return ans; } static long powmod(long r, long e, int mod) { long ans = 1; r %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * r) % mod); e >>= 1; r = (int) ((r * 1l * r) % mod); } return ans; } static int ceil(int a, int b) { int ans = a / b; return a % b == 0 ? ans : ans + 1; } static long ceil(long a, long b) { long ans = a / b; return a % b == 0 ? ans : ans + 1; } static HashMap<Integer, Integer> compress(int a[]) { TreeSet<Integer> ts = new TreeSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int x : a) ts.add(x); for (int x : ts) { hm.put(x, hm.size() + 1); } return hm; } // Returns nCr % p static int C[]; static int nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; if (C[r] != 0) return C[r]; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public int[] intArr(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } return a; } public long[] longArr(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = nextLong(); } return a; } 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(); } } public static void shuffle(int[] times2) { int n = times2.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = times2[i]; times2[i] = times2[r]; times2[r] = tmp; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
385627798eac38b4b9288f9c949ca392
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
// Main Code at the Bottom import java.util.*; import java.io.*; public class Main{ //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; //env=true; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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 long MOD=(long)1e9+7; //debug static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Global variables and functions //Main function(The main code starts from here) public static void main (String[] args) throws java.lang.Exception { int test=1; //test=sc.nextInt(); while(test-->0) { int n=sc.nextInt(),a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); int dp[]=new int[n],cnt[]=new int[n+1]; HashMap<Integer,int[]> idx=new HashMap<>(); for(int i=0;i<n;i++) { if(!idx.containsKey(a[i])) idx.put(a[i], new int[] {i,i}); else idx.get(a[i])[1]=i; } for(int i=n-1;i>=0;i--) { cnt[a[i]]++; if(idx.get(a[i])[0] == i) { int r=idx.get(a[i])[1]; dp[i]=cnt[a[i]]+(r+1>=n?0:dp[r+1]); dp[i]=Math.max(dp[i], i+1>=n?0:dp[i+1]); } else dp[i]=Math.max(i+1>=n?0:dp[i+1],cnt[a[i]]); } out.println(n-dp[0]); } out.flush(); out.close(); } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
fe950eb4b722cc3807fb94e2eebcd75a
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; public void solve() throws IOException { //int t = readInt(); int n = readInt(); int arr[]=new int[n+2]; for(int i =1;i<=n;i++) arr[i]= readInt(); ArrayList<edge> e= new ArrayList<edge>(); int count[]=new int[n+2]; int max[]=new int[n+2]; int first[]=new int[n+2]; int last[]=new int[n+2]; for(int i =n;i>=1;i--) { if(last[arr[i]]==0) { last[arr[i]]=i; } first[arr[i]]=i; count[arr[i]]++; max[i]=Math.max(max[i+1], count[arr[i]]); } e.add(new edge(0,0,0)); for(int i=1;i<=n;i++) { if(first[i]!=0) e.add(new edge(first[i],last[i],count[i])); } Collections.sort(e); int gal =0; int ans[]=new int [e.size()+1]; for(int i =1;i<e.size();i++) { int fir = e.get(i).f; int en = e.get(i).e; int left =0; int right =i-1; int lo =0; while(left<=right) { int mid = left + (right-left)/2; if(e.get(mid).e<=fir) { lo = mid; left=mid+1; } else { right=mid-1; } } gal = Math.max(gal, ans[lo]+max[en+1]+e.get(i).val); ans[i]= ans[lo]+ e.get(i).val; ans[i]= Math.max(ans[i-1],ans[i]); } out.println(n-gal); } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int f ; int e; int val; edge(int u, int v, int val) { this.f=u; this.e=v; this.val= val; } public int compareTo(edge e) { return this.e-e.e; } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
2b4271f42e9e7f3b4f7edb7b42942dbc
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.util.*; import java.io.*; public class E_1481 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] array = sc.nextIntArray(n); int[] f = new int[n + 1], l = new int[n + 1], r = new int[n + 1]; Arrays.fill(l, -1); for(int i = 0; i < n; i++) { f[array[i]]++; if(l[array[i]] == -1) l[array[i]] = i; r[array[i]] = i; } int[] cf = new int[n + 1]; int[] dp = new int[n + 1]; for(int i = n - 1; i >= 0; i--) { cf[array[i]]++; dp[i] = dp[i + 1]; if(l[array[i]] == i) dp[i] = Math.max(dp[i], f[array[i]] + dp[r[array[i]] + 1]); else dp[i] = Math.max(dp[i], cf[array[i]]); } pw.println(n - dp[0]); pw.flush(); } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) array[i] = new Integer(nextInt()); return array; } public long[] nextLongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public double[] nextDoubleArray(int n) throws IOException { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } public static int[] shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
b4bd0688fd7043bca7ef0761957fca3f
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
/******************************************************************************* * author : dante1 * created : 07/02/2021 14:54 *******************************************************************************/ import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // import java.math.BigInteger; import java.util.*; public class e { public static void main(String[] args) { int n = in.nextInt(); int[] a = new int[n]; int[] f = new int[n]; int[] cf = new int[n]; Integer[][] range = new Integer[n][2]; for (int i = 0; i < n; i++) { a[i] = in.nextInt()-1; f[a[i]]++; if (range[a[i]][0] == null) { range[a[i]][0] = i; } range[a[i]][1] = i; } int[] dp = new int[n+1]; for (int i = n-1; i >= 0; i--) { dp[i] = dp[i+1]; cf[a[i]]++; if (i == range[a[i]][0]) { dp[i] = Math.max(f[a[i]] + dp[1 + range[a[i]][1]], dp[i]); } else { dp[i] = Math.max(cf[a[i]], dp[i]); } } out.println(n-dp[0]); out.flush(); } // Handle I/O static int MOD = (int) (1e9 + 7); static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = nextInt(); } return arr; } long nextLong() { return Long.parseLong(next()); } long[] readLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; i++) { arr[i] = nextLong(); } return arr; } double nextDouble() { return Double.parseDouble(next()); } double[] readDoubleArray(int size) { double[] arr = new double[size]; for (int i = 0; i < size; i++) { arr[i] = nextDouble(); } return arr; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
6c2e2365dc6ac36c885df7c76cf007ae
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.util.*; import java.io.*; public class codeforces { static int n; static int[]a; static Integer[]fir; static Integer[]las; public static void main(String[] args) throws Exception { n=sc.nextInt(); a=sc.nextIntArray(n); fir=new Integer[n]; las=new Integer[n]; int[]cou=new int[n]; int[]dp=new int[n+1]; for(int i=0;i<n;i++) { if(fir[a[i]-1]==null)fir[a[i]-1]=i; las[a[i]-1]=i; } for(int i=n-1;i>-1;i--) { dp[i]=dp[i+1]; cou[a[i]-1]++; if(i==fir[a[i]-1]) { dp[i]=Math.max(dp[i],dp[las[a[i]-1]+1]+cou[a[i]-1] ); }else { dp[i]=Math.max(dp[i],cou[a[i]-1] ); } } pw.println(n-dp[0]); pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
3c0ff449629ad98085c16eb8569a5466
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
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; import java.util.TreeMap; public class e { public static void main(String[] args) { FastScanner scan=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int n=scan.nextInt(); first=new int[n]; last=new int[n]; Arrays.fill(first,-1); a=new int[n]; int[] sort=new int[n]; for(int i=0;i<n;i++) { a[i]=scan.nextInt(); sort[i]=a[i]; } Arrays.sort(sort); TreeMap<Integer,Integer> map=new TreeMap<>(); int ct=0; for(int i=0;i<n;i++) { if(!map.containsKey(sort[i])) map.put(sort[i],ct++); } freq=new int[n]; for(int i=0;i<n;i++) { a[i]=map.get(a[i]); if(first[a[i]]==-1) first[a[i]]=i; last[a[i]]=i; } dp=new int[n+1]; Arrays.fill(dp,-1); //dp[i]=max things staying in place in the suffix from i to n? dp[n]=0; for(int i=n-1;i>=0;i--) { freq[a[i]]++; //we move everything in the range of first[a[i]] to last[a[i]] that isn't equal to a[i]. //i.e. we keep freq[a[i]] things if(i==first[a[i]]) dp[i]=Math.max(dp[i],freq[a[i]]+dp[last[a[i]]+1]); //we may also want to keep all instances of a[i] thus far in the same spot //and move everything else dp[i]=Math.max(dp[i],freq[a[i]]); //and just move a single boo dp[i]=Math.max(dp[i],dp[i+1]); } out.println(n-dp[0]); out.close(); } static int[] first,last; static int[] dp; static int[] a; static int[] freq; 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
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
8b117af63fcb67a86a4db9b1c8e2994b
train_107.jsonl
1612535700
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class G { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = 1; for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(); int[] freq = new int[n + 1], min = new int[n + 1], max = new int[n + 1]; int[] dp = new int[n + 1], a = new int[n + 1]; for(int i = n; i > 0; i--) a[i] = scan.nextInt(); for(int i = 1; i <= n; i++) { max[a[i]] = i; if(min[a[i]] == 0) min[a[i]] = i; } for(int i = 1; i <= n; i++) { dp[i] = dp[i - 1]; freq[a[i]]++; if(max[a[i]] == i) { dp[i] = Math.max(dp[i], freq[a[i]] + dp[min[a[i]] - 1]); } else dp[i] = Math.max(dp[i], freq[a[i]]); } out.println(n - dp[n]); } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n1 2 2 1 3", "5\n1 2 2 1 1"]
2 seconds
["2", "1"]
NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example: take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$; take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
ed4693d015c9125ae77b9bca0139a135
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.
2,500
Output the minimum number of operations to make the shelf beautiful.
standard output
PASSED
e8a57e94d49d9c4552a559d944564a51
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; //import javafx.util.*; public final class B { static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<ArrayList<Integer>> g; static long mod=1000000007; static int D1[],D2[],par[]; static boolean set[]; public static void main(String args[])throws IOException { int T=i(); outer :while(T-->0) { int N=i(),M=i(); char G[][]=new char[N][N]; for(int i=0; i<N; i++)G[i]=in.next().toCharArray(); int a=-1,b=-1,c=-1; if(M%2!=0) { ans.append("YES\n"); print(1,2,M); } else { for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { if(i==j)continue; if(G[i][j]==G[j][i]) { ans.append("YES\n"); print(i+1,j+1,M); continue outer; } } } if(N<=2) { ans.append("NO\n"); continue outer; } for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { if(i==j)continue; char ch=G[i][j]; if(count(G[j],ch)>0) { a=i+1; b=j+1; c=findchar(0,ch,G[j])+1; break; } } } if(M%4==0) { ans.append("YES\n"); ans.append(b+" "); int tx=M/4; while(tx-->0) ans.append(c+" "+b+" "); tx=M/4; while(tx-->0) ans.append(a+" "+b+" "); ans.append("\n"); } else { ans.append("YES\n"); ans.append(a+" "); for(int i=1; i<=M; i++) { int tx=i%4; if(tx==0)ans.append(a+" "); else if(tx==2)ans.append(c+" "); else ans.append(b+" "); } ans.append("\n"); } } } System.out.println(ans); } static int findchar(int index,char ch,char A[]) { for(int i=index; i<A.length; i++) { if(A[i]==ch)return i; } return 0; } static int count(char A[],char x) { int c=0; for(char ct:A)if(ct==x)c++; return c; } static void print(int a,int b,int M) { for(int i=0; i<=M; i++) { if(i%2==0) { ans.append(a+" "); } else { ans.append(b+" "); } } ans.append("\n"); } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { par[a]+=par[b]; //transfers the size par[b]=a; //changes the parent } } static ArrayList<Integer> IND(int B[],HashMap<Integer,Integer> mp) { ArrayList<Integer> A=new ArrayList<>(); for(int i:B) { if(mp.containsKey(i)) { A.add(i); int f=mp.get(i)-1; if(f==0) mp.remove(i); else mp.put(i, f); } } return A; } static HashMap<Integer,Integer> hash(int A[],int index) { HashMap<Integer,Integer> mp=new HashMap<Integer,Integer>(); for(int i=index; i<A.length; i++) { int f=mp.getOrDefault(A[i], 0)+1; mp.put(A[i], f); } return mp; } static void swap(char A[],int a,int b) { char ch=A[a]; A[a]=A[b]; A[b]=ch; } static long lower_Bound(long A[],int low,int high, long x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void setGraph(int N) { //set=new boolean[N+1]; //size=new int[N+1]; //par=new int[N+1]; g=new ArrayList<ArrayList<Integer>>(); //tg=new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=N; i++) { g.add(new ArrayList<Integer>()); //tg.add(new ArrayList<Integer>()); } } static long pow(long a,long b) { long mod=1000000007; long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } 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 boolean isPrime(long 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 long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } //Debugging Functions Starts static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } //Debugging Functions END //---------------------- //IO FUNCTIONS STARTS static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } //IO FUNCTIONS END } class paint implements Comparable<paint> { int color,index; paint(int c,int i) { color=c; index=i; } public int compareTo(paint X) { return this.color-X.color; } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader 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\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
a5a2897008b02d6a84c819090825ea52
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.lang.*; public class Main{ public static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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); } public static void sortbyColumn(int arr[][], int col) { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(final int[] entry1, final int[] entry2) { if (entry1[col] > entry2[col]) return 1; else return -1; } }); } static long func(long a[],int size,int s){ long max1=a[s]; long maxc=a[s]; for(int i=s+1;i<size;i++){ maxc=Math.max(a[i],maxc+a[i]); max1=Math.max(maxc,max1); } return max1; } public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> { public U x; public V y; public Pair(U x, V y) { this.x = x; this.y = y; } public int hashCode() { return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<U, V> p = (Pair<U, V>) o; return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y)); } public int compareTo(Pair<U, V> b) { int cmpU = x.compareTo(b.x); return cmpU != 0 ? cmpU : y.compareTo(b.y); } public String toString() { return String.format("(%s, %s)", x.toString(), y.toString()); } } static class MultiSet<U extends Comparable<U>> { public int sz = 0; public TreeMap<U, Integer> t; public MultiSet() { t = new TreeMap<>(); } public void add(U x) { t.put(x, t.getOrDefault(x, 0) + 1); sz++; } public void remove(U x) { if (t.get(x) == 1) t.remove(x); else t.put(x, t.get(x) - 1); sz--; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static long myceil(long a, long b){ return (a+b-1)/b; } static long C(long n,long r){ long count=0,temp=n; long ans=1; long num=n-r+1,div=1; while(num<=n){ ans*=num; //ans+=MOD; ans%=MOD; ans*=mypow(div,MOD-2); //ans+=MOD; ans%=MOD; num++; div++; } ans+=MOD; return ans%MOD; } static long fact(long a){ long i,ans=1; for(i=1;i<=a;i++){ ans*=i; ans%=MOD; } return ans%=MOD; } static void sieve(int n){ is_sieve[0]=1; is_sieve[1]=1; int i,j,k; for(i=2;i<n;i++){ if(is_sieve[i]==0){ sieve[i]=i; tr.add(i); for(j=i*i;j<n;j+=i){ if(j>n||j<0){ break; } is_sieve[j]=1; sieve[j]=i; } } } } static void calc(int n){ int i,j; dp[n-1]=0; if(n>1) dp[n-2]=1; for(i=n-3;i>=0;i--){ long ind=n-i-1; dp[i]=((ind*(long)mypow(10,ind-1))%MOD+dp[i+1])%MOD; } } static long mypow(long x,long y){ long temp; if( y == 0) return 1; temp = mypow(x, y/2); if (y%2 == 0) return (temp*temp)%MOD; else return ((x*temp)%MOD*(temp)%MOD)%MOD; } static long dist[],dp[]; static int visited[][]; static ArrayList<Integer> adj[]; //static int dp[][][]; static int R,G,B,MOD=1000000007; static int[] par,size; static int[] sieve,is_sieve; static TreeSet<Integer> tr; static char ch[][], ch1[][]; public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter w = new PrintWriter(outputStream); int t,i,j,tno=0,tte; t=in.nextInt(); //t=1; tte=t; while(t-->0){ tno++; int n,m; n=in.nextInt(); m=in.nextInt(); String s[]=new String[n]; char ch[][]=new char[n][]; int has[][]=new int[n][2]; for(i=0;i<n;i++){ Arrays.fill(has[i],-1); } for(i=0;i<n;i++){ ch[i]=in.next().toCharArray(); for(j=0;j<n;j++){ if(i!=j) has[i][ch[i][j]-'a']=j; } } if(m%2==0){ int flag=0,x=0,y=0; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(i!=j){ if(ch[i][j]==ch[j][i]){ x=i; y=j; flag=1; break; } } } if(flag==1){ break; } } if(flag==1){ w.println("YES"); for(i=0;i<m+1;i++){ if(i%2==0){ w.print(x+1+" "); }else{ w.print(y+1+" "); } } w.println(); }else{ int fl=0; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(i==j){ continue; } if(has[j][ch[i][j]-'a']==-1){ continue; } w.println("YES"); int cur=has[j][ch[i][j]-'a']; if((m/2)%2!=0){ fl=1; for(int k = 0 ;k < m + 1;k++){ if(k % 4 == 0) w.print(i+1+" "); else if(k % 4 == 2) w.print(cur+1+" "); else w.print(j+1+" "); } }else{ fl=1; w.print(j+1+" "); fl=1; for(int k = 0 ;k < m / 2;k++){ if(k % 2!=0) w.print(j+1+" "); else w.print(cur+1+" "); } for(int k = 0 ;k < m / 2;k++){ if(k%2!=0) w.print(j+1+" "); else w.print(i+1+" "); } } if(fl==1){ break; } } if(fl==1){ break; } } if(fl!=1){ w.println("NO"); } } }else{ int flag=0,x=0,y=0; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(i!=j){ x=i; y=j; flag=1; break; } } if(flag==1){ break; } } w.println("YES"); for(i=0;i<m+1;i++){ if(i%2==0){ w.print(x+1+" "); }else{ w.print(y+1+" "); } } w.println(); } } w.close(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
7cf4e0a3d38c94c7db387f899d9ea0e2
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
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.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static final int mod = 998244353; static int t = 1; static double epsilon = 0.00000001; static boolean[] isPrime; static int[] smallestFactorOf; static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3; @SuppressWarnings({"unused"}) public static void main(String[] args) throws Exception { t = fr.nextInt(); OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(), m = fr.nextInt(); char[][] grid = new char[n][]; for (int i = 0; i < n; i++) grid[i] = fr.next().toCharArray(); if (m % 2 == 1) { out.println("YES"); for (int i = 0; i < m + 1; i++) out.print(((i % 2 == 0) ? 1 : 2) + " "); out.println(); continue OUTER; } assert m % 2 == 0; // Observations: // 1. The task is to determine a palindrome path of length 'm'. // 2. If there's: // a. 'a' cycle // b. 'b' cycle // The answer is trivial. // -- // We just keep going through the cycle and all 'm' letters // are equal. // -- // Alternatively, if there's some path of length >= m, we have // the answer trivially again. for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (i == j) continue; if (grid[i][j] == grid[j][i]) { // looooooooop int first = i + 1, second = j + 1; out.println("YES"); out.print(first + " "); for (int k = 0; k < m; k++) out.print((k % 2 == 1 ? first : second) + " "); out.println(); continue OUTER; } } /*ArrayList<Integer> aAns = cPath(grid, 'a', m); ArrayList<Integer> bAns = cPath(grid, 'b', m); if (!aAns.isEmpty()) { out.println("YES"); for (int i : aAns) out.print((i + 1) + " "); out.println(); continue OUTER; } if (!bAns.isEmpty()) { out.println("YES"); for (int i : bAns) out.print((i + 1) + " "); out.println(); continue OUTER; }*/ // 3. If there's no cycle, it implies: // grid[i][j] = !grid[j][i] // -- // grid[i][j] == a => grid[j][i] = b // grid[i][j] == b => grid[j][i] = a // 4. Claim: If there are two consecutive same characters, // the answer always exists. // -- // PROOF: // For 2, we can just do 'aa' // For 4, we can do 'abba' // For any other power of 2, we can just repeat // -- // For any number having an odd prime factor, we // can do 'ababab..ababa' and repeat by multiple. // -- // Q.E.D. if (n == 2) { out.println("NO"); continue OUTER; } // we have to find 2 consecutive edges (3 nodes) int[][] cEdgeFrom = new int[2][n]; for (int i = 0; i < 2; i++) for (int j = 0; j < n; j++) cEdgeFrom[i][j] = -1; for (int i = 0; i < n; i++) { char[] edges = grid[i]; for (int j = 0; j < n; j++) if (edges[j] != '*') cEdgeFrom[edges[j] - 'a'][i] = j; } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (i == j) continue; char c = grid[i][j]; // we have to find cEdgeFrom[c][j] int k = cEdgeFrom[c - 'a'][j]; if (k == -1) continue; // (i, j, k) is the thing // i -> j -> k => both edges c // i <- j <- k => both edges !c out.println("YES"); if (m == 2) { out.println((i + 1) + " " + (j + 1) + " " + (k + 1)); } else if ((m / 2) % 2 == 1) { // 2 times (m / 2) int first = i + 1, second = j + 1; // abababa...baba 2 times out.print(first + " "); for (int tt = 0; tt < m / 2; tt++) out.print(((tt % 2 == 1) ? first : second) + " "); first = j + 1; second = k + 1; for (int tt = 0; tt < m / 2; tt++) out.print(((tt % 2 == 1) ? first : second) + " "); out.println(); } else { // abba abba abba .. even times // j (k j i j) (k j i j) (k j i j) ... out.print((j + 1) + " "); for (int tt = 0; tt < m / 4; tt++) out.print((k + 1) + " " + (j + 1) + " " + (i + 1) + " " + (j + 1) + " "); out.println(); } continue OUTER; } out.println("NO"); } out.close(); } static ArrayList<Integer> cPath(char[][] grid, char c, int m) { ArrayList<Integer> ans = new ArrayList<>(); // we return a cyclic path or a path of length >= m (path.size() >= m + 1) int n = grid.length; Digraph dg = new Digraph(n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (grid[i][j] == c) dg.addEdge(i, j); // we have to find a cycle Stack<Integer> path = new Stack<>(); for (int i = 0; i < n && path.isEmpty(); i++) cycDFS(i, dg, path, m); for (int i : path) ans.add(i); return ans; } static void cycDFS(int current, Digraph dg, Stack<Integer> path, int m) { if (path.size() >= m + 1) { // don't touch it return; } path.push(current); for (int adj : dg.adj(current)) cycDFS(adj, dg, path, m); if (path.size() < m + 1) path.pop(); } public static long[][] GCDSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; } else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeGCDQ(long[][] table, int l, int r) { // [a,b) assert l <= r; if(l > r)return 1; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return gcd(table[t][l], table[t][r-(1<<t)]); } static SegNode answer(SegNode node, int left, int right, int reqLeft, int reqRight) { if (reqLeft > reqRight) return new SegNode(0, 0, 0); if (left == reqLeft && right == reqRight) return node; int mid = left + (right - left) / 2; return combine(answer(node.left, left, mid, reqLeft, Math.min(reqRight, mid)), answer(node.right, mid + 1, right, Math.max(reqLeft, mid + 1), reqRight)); } static SegNode combine(SegNode leftNode, SegNode rightNode) { SegNode node = new SegNode(); int newMatchn = Math.min(leftNode.bachOp, rightNode.bachCl); node.matchn = leftNode.matchn + rightNode.matchn + newMatchn; node.bachOp = leftNode.bachOp + rightNode.bachOp - newMatchn; node.bachCl = leftNode.bachCl + rightNode.bachCl - newMatchn; return node; } static SegNode construct(SegNode node, int left, int right, char[] s) { if (left > right) return null; if (left == right) { int matchn = 0, bbo = (s[left] == '(' ? 1 : 0), bbc = 1 - bbo; return node = new SegNode(matchn, bbo, bbc); } int mid = left + (right - left) / 2; node = new SegNode(); SegNode leftNode = node.left = construct(node.left, left, mid, s); SegNode rightNode = node.right = construct(node.right, mid + 1, right, s); return node = combine(leftNode, rightNode); } static class SegNode { int matchn, bachOp, bachCl; SegNode left, right; SegNode() {} SegNode(int mm, int bbo, int bbc) { matchn = mm; bachOp = bbo; bachCl = bbc; left = right = null; } } static class Trie { TrieNode root; Trie(char[][] strings) { root = new TrieNode('A', false); construct(root, strings); } public Stack<String> set(TrieNode root) { Stack<String> set = new Stack<>(); StringBuilder sb = new StringBuilder(); for (TrieNode next : root.next) collect(sb, next, set); return set; } private void collect(StringBuilder sb, TrieNode node, Stack<String> set) { if (node == null) return; sb.append(node.character); if (node.isTerminal) set.add(sb.toString()); for (TrieNode next : node.next) collect(sb, next, set); if (sb.length() > 0) sb.setLength(sb.length() - 1); } private void construct(TrieNode root, char[][] strings) { // we have to construct the Trie for (char[] string : strings) { if (string.length == 0) continue; root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0); if (root.next[string[0] - 'a'] != null) root.isLeaf = false; } } private TrieNode put(TrieNode node, char[] string, int idx) { boolean isTerminal = (idx == string.length - 1); if (node == null) node = new TrieNode(string[idx], isTerminal); node.character = string[idx]; node.isTerminal |= isTerminal; if (!isTerminal) { node.isLeaf = false; node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1); } return node; } class TrieNode { char character; TrieNode[] next; boolean isTerminal, isLeaf; boolean canWin, canLose; TrieNode(char c, boolean isTerminallll) { character = c; isTerminal = isTerminallll; next = new TrieNode[26]; isLeaf = true; } } } static class Pair { int u, v; Pair(int ss, int cc) { u = ss; v = cc; } } static void shortestBFS(int src, int[] ans, UGraph ug) { int n = ug.V(); Arrays.fill(ans, Integer.MAX_VALUE / 10); // we will just carry out a BFS from src PriorityQueue<Pair> pq = new PriorityQueue<>((Pair s1, Pair s2) -> Integer.compare(s1.u, s2.u)); boolean[] marked = new boolean[n]; marked[src] = true; pq.add(new Pair(src, 0)); while (!pq.isEmpty()) { Pair best = pq.poll(); ans[best.v] = best.u; for (int adj : ug.adj(best.v)) if (!marked[adj]) { marked[adj] = true; pq.add(new Pair(adj, best.u + 1)); } } } static class Edge implements Comparable<Edge> { int from, to; long weight; int id; // int hash; Edge(int fro, int t, long wt, int i) { from = fro; to = t; id = i; weight = wt; // hash = Objects.hash(from, to, weight); } /*public int hashCode() { return hash; }*/ public int compareTo(Edge that) { return Long.compare(this.id, that.id); } } public static long[][] minSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMinQ(long[][] table, int l, int r) { // [a,b) assert l <= r; if(l >= r)return Integer.MAX_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.min(table[t][l], table[t][r-(1<<t)]); } public static long[][] maxSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMaxQ(long[][] table, int l, int r) { // [a,b) assert l <= r; if(l >= r)return Integer.MIN_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.max(table[t][l], table[t][r-(1<<t)]); } static int treeDiameter(UGraph ug) { int n = ug.V(); int farthest = -1; int[] distTo = new int[n]; diamDFS(0, -1, 0, ug, distTo); int maxDist = -1; for (int i = 0; i < n; i++) if (maxDist < distTo[i]) { maxDist = distTo[i]; farthest = i; } distTo = new int[n]; diamDFS(farthest, -1, 0, ug, distTo); return Arrays.stream(distTo).max().getAsInt(); } static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) { distTo[current] = dist; for (int adj : ug.adj(current)) if (adj != from) diamDFS(adj, current, dist + 1, ug, distTo); } static class LCA { int[] height, first, segtree; ArrayList<Integer> euler; boolean[] visited; int n; LCA(UGraph ug, int root) { n = ug.V(); height = new int[n]; first = new int[n]; euler = new ArrayList<>(); visited = new boolean[n]; dfs(ug, root, 0); int m = euler.size(); segtree = new int[m * 4]; build(1, 0, m - 1); } void dfs(UGraph ug, int node, int h) { visited[node] = true; height[node] = h; first[node] = euler.size(); euler.add(node); for (int adj : ug.adj(node)) { if (!visited[adj]) { dfs(ug, adj, h + 1); euler.add(node); } } } void build(int node, int b, int e) { if (b == e) { segtree[node] = euler.get(b); } else { int mid = (b + e) / 2; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); int l = segtree[node << 1], r = segtree[node << 1 | 1]; segtree[node] = (height[l] < height[r]) ? l : r; } } int query(int node, int b, int e, int L, int R) { if (b > R || e < L) return -1; if (b >= L && e <= R) return segtree[node]; int mid = (b + e) >> 1; int left = query(node << 1, b, mid, L, R); int right = query(node << 1 | 1, mid + 1, e, L, R); if (left == -1) return right; if (right == -1) return left; return height[left] < height[right] ? left : right; } int lca(int u, int v) { int left = first[u], right = first[v]; if (left > right) { int temp = left; left = right; right = temp; } return query(1, 0, euler.size() - 1, left, right); } } static class FenwickTree { long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rsq(int ind) { assert ind > 0; long sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public long rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static boolean[] prefMatchesSuff(char[] s) { int n = s.length; boolean[] res = new boolean[n + 1]; int[] pi = prefixFunction(s); res[0] = true; for (int p = n; p != 0; p = pi[p]) res[p] = true; return res; } static int[] prefixFunction(char[] s) { int k = s.length; int[] pfunc = new int[k + 1]; pfunc[0] = pfunc[1] = 0; for (int i = 2; i <= k; i++) { pfunc[i] = 0; for (int p = pfunc[i - 1]; p != 0; p = pfunc[p]) if (s[p] == s[i - 1]) { pfunc[i] = p + 1; break; } if (pfunc[i] == 0 && s[i - 1] == s[0]) pfunc[i] = 1; } return pfunc; } static class Point implements Comparable<Point> { long x; long y; long z; long id; // private int hashCode; Point() { x = z = y = 0; // this.hashCode = Objects.hash(x, y, cost); } Point(Point p) { this.x = p.x; this.y = p.y; this.z = p.z; this.id = p.id; // this.hashCode = Objects.hash(x, y, cost); } Point(long x, long y, long z, long id) { this.x = x; this.y = y; this.z = z; this.id = id; // this.hashCode = Objects.hash(x, y, id); } Point(long a, long b) { this.x = a; this.y = b; this.z = 0; // this.hashCode = Objects.hash(a, b); } Point(long x, long y, long id) { this.x = x; this.y = y; this.id = id; } @Override public int compareTo(Point o) { if (this.x < o.x) return -1; if (this.x > o.x) return 1; if (this.y < o.y) return -1; if (this.y > o.y) return 1; if (this.z < o.z) return -1; if (this.z > o.z) return 1; return 0; } @Override public boolean equals(Object that) { return this.compareTo((Point) that) == 0; } /*@Override public int hashCode() { return this.hashCode; }*/ } static class BinaryLift { // FUNCTIONS: k-th ancestor and LCA in log(n) int[] parentOf; int maxJmpPow; int[][] binAncestorOf; int n; int[] lvlOf; // How this works? // a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}. // b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we // lift level in the tree. public BinaryLift(UGraph tree) { n = tree.V(); maxJmpPow = logk(n, 2) + 1; parentOf = new int[n]; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); parentConstruct(0, -1, tree, 0); binConstruct(); } // TODO: Implement lvlOf[] initialization public BinaryLift(int[] parentOf) { this.parentOf = parentOf; n = parentOf.length; maxJmpPow = logk(n, 2) + 1; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); UGraph tree = new UGraph(n); for (int i = 1; i < n; i++) tree.addEdge(i, parentOf[i]); binConstruct(); parentConstruct(0, -1, tree, 0); } private void parentConstruct(int current, int from, UGraph tree, int depth) { parentOf[current] = from; lvlOf[current] = depth; for (int adj : tree.adj(current)) if (adj != from) parentConstruct(adj, current, tree, depth + 1); } private void binConstruct() { for (int node = 0; node < n; node++) for (int lvl = 0; lvl < maxJmpPow; lvl++) binConstruct(node, lvl); } private int binConstruct(int node, int lvl) { if (node < 0) return -1; if (lvl == 0) return binAncestorOf[node][lvl] = parentOf[node]; if (node == 0) return binAncestorOf[node][lvl] = -1; if (binAncestorOf[node][lvl] != -1) return binAncestorOf[node][lvl]; return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1); } // return ancestor which is 'k' levels above this one public int ancestor(int node, int k) { if (node < 0) return -1; if (node == 0) if (k == 0) return node; else return -1; if (k > (1 << maxJmpPow) - 1) return -1; if (k == 0) return node; int ancestor = node; int highestBit = Integer.highestOneBit(k); while (k > 0 && ancestor != -1) { ancestor = binAncestorOf[ancestor][logk(highestBit, 2)]; k -= highestBit; highestBit = Integer.highestOneBit(k); } return ancestor; } public int lca(int u, int v) { if (u == v) return u; // The invariant will be that 'u' is below 'v' initially. if (lvlOf[u] < lvlOf[v]) { int temp = u; u = v; v = temp; } // Equalizing the levels. u = ancestor(u, lvlOf[u] - lvlOf[v]); if (u == v) return u; // We will now raise level by largest fitting power of two until possible. for (int power = maxJmpPow - 1; power > -1; power--) if (binAncestorOf[u][power] != binAncestorOf[v][power]) { u = binAncestorOf[u][power]; v = binAncestorOf[v][power]; } return ancestor(u, 1); } } static class DFSTree { // NOTE: The thing is made keeping in mind that the whole // input graph is connected. UGraph tree; UGraph backUG; int hasBridge; int n; DFSTree(UGraph ug) { this.n = ug.V(); tree = new UGraph(n); hasBridge = -1; backUG = new UGraph(n); treeCalc(0, -1, new boolean[n], ug); } private void treeCalc(int current, int from, boolean[] marked, UGraph ug) { if (marked[current]) { // This is a backEdge. backUG.addEdge(from, current); return; } if (from != -1) tree.addEdge(from, current); marked[current] = true; for (int adj : ug.adj(current)) if (adj != from) treeCalc(adj, current, marked, ug); } public boolean hasBridge() { if (hasBridge != -1) return (hasBridge == 1); // We have to determine the bridge. bridgeFinder(); return (hasBridge == 1); } int[] levelOf; int[] dp; private void bridgeFinder() { // Finding the level of each node. levelOf = new int[n]; // Applying DP solution. // dp[i] -> Highest level reachable from subtree of 'i' using // some backEdge. dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE / 100); dpDFS(0, -1, 0); // Now, we will check each edge and determine whether its a // bridge. for (int i = 0; i < n; i++) for (int adj : tree.adj(i)) { // (i -> adj) is the edge. if (dp[adj] > levelOf[i]) hasBridge = 1; } if (hasBridge != 1) hasBridge = 0; } private int dpDFS(int current, int from, int lvl) { levelOf[current] = lvl; dp[current] = levelOf[current]; for (int back : backUG.adj(current)) dp[current] = Math.min(dp[current], levelOf[back]); for (int adj : tree.adj(current)) if (adj != from) dp[current] = Math.min(dp[current], dpDFS(adj, current, lvl + 1)); return dp[current]; } } static class UnionFind { // Uses weighted quick-union with path compression. private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } } static class SegmentTree { private Node[] heap; private long[] array; private int size; public SegmentTree(long[] array) { this.array = Arrays.copyOf(array, array.length); //The max size of this array is about 2 * 2 ^ log2(n) + 1 size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1))); heap = new Node[size]; build(1, 0, array.length); } public int size() { return array.length; } //Initialize the Nodes of the Segment tree private void build(int v, int from, int size) { heap[v] = new Node(); heap[v].from = from; heap[v].to = from + size - 1; if (size == 1) { heap[v].sum = array[from]; heap[v].min = array[from]; heap[v].max = array[from]; } else { //Build childs build(2 * v, from, size / 2); build(2 * v + 1, from + size / 2, size - size / 2); heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum; //min = min of the children heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); heap[v].max = Math.max(heap[2 * v].max, heap[2 * v + 1].max); } } public long rsq(int from, int to) { return rsq(1, from, to); } private long rsq(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Sum without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return (to - from + 1) * n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].sum; } if (intersects(from, to, n.from, n.to)) { propagate(v); long leftSum = rsq(2 * v, from, to); long rightSum = rsq(2 * v + 1, from, to); return leftSum + rightSum; } return 0; } public long rMinQ(int from, int to) { return rMinQ(1, from, to); } private long rMinQ(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Min value without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].min; } if (intersects(from, to, n.from, n.to)) { propagate(v); long leftMin = rMinQ(2 * v, from, to); long rightMin = rMinQ(2 * v + 1, from, to); return Math.min(leftMin, rightMin); } return Integer.MAX_VALUE; } public long rMaxQ(int from, int to) { return rMaxQ(1, from, to); } private long rMaxQ(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Min value without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].max; } if (intersects(from, to, n.from, n.to)) { propagate(v); long leftMax = rMaxQ(2 * v, from, to); long rightMax = rMaxQ(2 * v + 1, from, to); return Math.max(leftMax, rightMax); } return Integer.MIN_VALUE; } public void update(int from, int to, long value) { update(1, from, to, value); } private void update(int v, int from, int to, long value) { //The Node of the heap tree represents a range of the array with bounds: [n.from, n.to] Node n = heap[v]; if (contains(from, to, n.from, n.to)) { change(n, value); } if (n.size() == 1) return; if (intersects(from, to, n.from, n.to)) { propagate(v); update(2 * v, from, to, value); update(2 * v + 1, from, to, value); n.sum = heap[2 * v].sum + heap[2 * v + 1].sum; n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); n.max = Math.max(heap[2 * v].max, heap[2 * v + 1].max); } } //Propagate temporal values to children private void propagate(int v) { Node n = heap[v]; if (n.pendingVal != null) { change(heap[2 * v], n.pendingVal); change(heap[2 * v + 1], n.pendingVal); n.pendingVal = null; //unset the pending propagation value } } //Save the temporal values that will be propagated lazily private void change(Node n, long value) { if (n.pendingVal == null) n.pendingVal = 0L; n.pendingVal += value; n.sum = n.size() * value; n.min = value; n.max += value; array[n.from] += value; } //Test if the range1 contains range2 private boolean contains(int from1, int to1, int from2, int to2) { return from2 >= from1 && to2 <= to1; } //check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2] private boolean intersects(int from1, int to1, int from2, int to2) { return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..) || from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..).. } //The Node class represents a partition range of the array. static class Node { long sum; long min; long max; //Here we store the value that will be propagated lazily Long pendingVal = null; int from; int to; int size() { return to - from + 1; } } } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { return super.put(key, super.getOrDefault(key, 0) + 1); } public Integer removeCM(T key) { int count = super.getOrDefault(key, -1); if (count == -1) return -1; if (count == 1) return super.remove(key); else return super.put(key, count - 1); } public Integer getCM(T key) { return super.getOrDefault(key, 0); } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static long dioGCD(long a, long b, long[] x0, long[] y0) { if (b == 0) { x0[0] = 1; y0[0] = 0; return a; } long[] x1 = new long[1], y1 = new long[1]; long d = dioGCD(b, a % b, x1, y1); x0[0] = y1[0]; y0[0] = x1[0] - y1[0] * (a / b); return d; } static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) { g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0); if (c % g[0] > 0) { return false; } x0[0] *= c / g[0]; y0[0] *= c / g[0]; if (a < 0) x0[0] = -x0[0]; if (b < 0) y0[0] = -y0[0]; return true; } static long[][] prod(long[][] mat1, long[][] mat2) { int n = mat1.length; long[][] prod = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // determining prod[i][j] // it will be the dot product of mat1[i][] and mat2[][i] for (int k = 0; k < n; k++) prod[i][j] += mat1[i][k] * mat2[k][j]; return prod; } static long[][] matExpo(long[][] mat, long power) { int n = mat.length; long[][] ans = new long[n][n]; if (power == 0) return null; if (power == 1) return mat; long[][] half = matExpo(mat, power / 2); ans = prod(half, half); if (power % 2 == 1) { ans = prod(ans, mat); } return ans; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static long hash(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(num + 1); HashMap<Integer, Integer> fnps = new HashMap<>(); while (num != 1) { fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1); num /= smallestFactorOf[num]; } return fnps; } static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } static int bsearch(int[] arr, int val, int lo, int hi) { // Returns the index of the first element // larger than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi) { // Returns the index of the first element // larger than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) { // Returns the index of the last element // smaller than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static long nCr(long n, long r, long[] fac) { long p = mod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long modDiv(long a, long b){return mod(a * power(b, gigamod - 2, gigamod));} static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();} static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();} static long mod(long a, long m){return(a%m+1000000L*m)%m;} static long mod(long num){return(num%gigamod+gigamod)%gigamod;} } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
a3c9f7c7d5b3802766787a26a7fc1535
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { static InputReader ir; static OutputPrinter op; static int n; static int m; static boolean graph[][]; public static void main(String[] args) throws IOException { ir = new InputReader(); op = new OutputPrinter(); int t = ir.nextInt(); for (int i = 0; i < t; i++) { n = ir.nextInt(); m = ir.nextInt(); graph = new boolean[n][n]; String line; for (int j = 0; j < n; j++) { line = ir.nextLine(); for (int k = 0; k < n; k++) { if (j != k) { if (line.charAt(k) == 'a') { graph[j][k] = false; } else { graph[j][k] = true; } } } } f(); } } public static void f() throws IOException { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (graph[i][j] == graph[j][i]) { op.writeln("YES"); for (int l = 0; l < m + 1; l++) { if (l != 0) { op.write(" "); } op.write(l % 2 == 0 ? i + 1 : j + 1); } op.writeln(); return; } } } if (m % 2 == 1) { op.writeln("YES"); for (int l = 0; l < m + 1; l++) { if (l != 0) { op.write(" "); } op.write(l % 2 == 0 ? 1 : 2); } op.writeln(); return; } if (n == 2) { op.writeln("NO"); return; } op.writeln("YES"); boolean zeroTo1 = graph[0][1]; boolean oneTo2 = graph[1][2]; boolean twoToZero = graph[2][0]; if (zeroTo1 == oneTo2) { if (m % 4 == 2) { int[] vals = {0, 1, 2, 1}; int cur = 0; for (int i =0; i < m + 1; i++) { if (i != 0) { op.write(" "); } op.write(vals[cur++] + 1); cur %= 4; } op.writeln(); } else { int[] vals = {1, 2, 1, 0}; int cur = 0; for (int i =0; i < m + 1; i++) { if (i != 0) { op.write(" "); } op.write(vals[cur++] + 1); cur %= 4; } op.writeln(); } } else if (oneTo2 == twoToZero) { if (m % 4 == 2) { int[] vals = {1, 2, 0, 2}; int cur = 0; for (int i =0; i < m + 1; i++) { if (i != 0) { op.write(" "); } op.write(vals[cur++] + 1); cur %= 4; } op.writeln(); } else { int[] vals = {2, 0, 2, 1}; int cur = 0; for (int i =0; i < m + 1; i++) { if (i != 0) { op.write(" "); } op.write(vals[cur++] + 1); cur %= 4; } op.writeln(); } } else { if (m % 4 == 2) { int[] vals = {2, 0, 1, 0}; int cur = 0; for (int i =0; i < m + 1; i++) { if (i != 0) { op.write(" "); } op.write(vals[cur++] + 1); cur %= 4; } op.writeln(); } else { int[] vals = {0, 1, 0, 2}; int cur = 0; for (int i =0; i < m + 1; i++) { if (i != 0) { op.write(" "); } op.write(vals[cur++] + 1); cur %= 4; } op.writeln(); } } } } /* 3 1 *aa b*a bb* 3 2 *aa b*a bb* 3 3 *aa b*a bb* 3 4 *aa b*a bb* 3 5 *aa b*a bb* 3 1 *bb a*a bb* */ class InputReader { public BufferedReader br; public StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() throws IOException { if (st == null) { st = new StringTokenizer(br.readLine()); } if (st.hasMoreElements()) { return Integer.parseInt(st.nextToken()); } else { st = new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } } public double nextDouble() throws IOException { if (st == null) { st = new StringTokenizer(br.readLine()); } if (st.hasMoreElements()) { return Double.parseDouble(st.nextToken()); } else { st = new StringTokenizer(br.readLine()); return Double.parseDouble(st.nextToken()); } } public String nextToken() throws IOException { if (st == null) { st = new StringTokenizer(br.readLine()); } if (st.hasMoreElements()) { return st.nextToken(); } else { st = new StringTokenizer(br.readLine()); return st.nextToken(); } } public String nextLine() throws IOException { return br.readLine(); } } class OutputPrinter { public PrintWriter pw; public OutputPrinter() { pw = new PrintWriter(new OutputStreamWriter(System.out), true); } public void write(char[] buf) throws IOException { pw.write(buf); pw.flush(); } public void writeln(char[] buf) throws IOException { write(buf); pw.write("\n"); pw.flush(); } public void write(String s) throws IOException { pw.write(s); pw.flush(); } public void writeln(String s) throws IOException { write(s); pw.write("\n"); pw.flush(); } public void write(int t) throws IOException { pw.write(Integer.toString(t)); pw.flush(); } public void writeln(int t) throws IOException { write(t); pw.write("\n"); pw.flush(); } public void write(double d) throws IOException { pw.write(Double.toString(d)); pw.flush(); } public void writeln(double d) throws IOException { write(d); pw.write("\n"); pw.flush(); } public void writeln() { pw.write("\n"); pw.flush(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
27b09a4bf9498f3346d2999fe1d38f2a
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
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 { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = sc.nextInt(); for(int t = 0; t<T; t++){ int N = sc.nextInt(), M = sc.nextInt(); char arr[][] = new char[N][N]; Node nodes[] = new Node[N]; for(int i = 0; i<N; i++){ nodes[i] = new Node(); String s = sc.next(); for(int j = 0; j<N; j++){ arr[i][j] = s.charAt(j); if(arr[i][j] == 'a')nodes[i].a_connect = j; else if(arr[i][j] == 'b')nodes[i].b_connect = j; } } int twoNoded1 = -1, twoNoded2 = -1; int threeNoded1 = -1, threeNoded2 = -1, threeNoded3 = -1; for(int i = 0; i<N; i++){ for(int j = 0; j<N; j++){ if(i == j)continue; if(arr[i][j] == arr[j][i]){ twoNoded1 = i + 1; twoNoded2 = j + 1; } if(arr[i][j] == 'a' && nodes[j].a_connect != -1){ threeNoded1 = i + 1; threeNoded2 = j + 1; threeNoded3 = nodes[j].a_connect + 1; } if(arr[i][j] == 'b' && nodes[j].b_connect != -1){ threeNoded1 = i + 1; threeNoded2 = j + 1; threeNoded3 = nodes[j].b_connect + 1; } } } if(twoNoded2 != -1){ out.println("YES"); for(int i = 0; i<M; i++)out.print((i % 2 == 0 ? twoNoded2 : twoNoded1) + " "); out.println((M % 2 == 0 ? twoNoded2 : twoNoded1)); } else{ if(M % 2 == 1){ out.println("YES"); for(int i = 0; i<M; i++)out.print((i % 2 == 0 ? 1 : 2) + " "); out.println((M % 2 == 0 ? 1 : 2)); } else if(N == 2)out.println("NO"); else{ out.println("YES"); if(M % 4 == 0){ int num = M / 4; String g = threeNoded2 + " " + threeNoded1 + " " + threeNoded2 + " " + threeNoded3 + " "; for(int i = 0; i<num; i++)out.print(g); out.println(threeNoded2); } else if(M == 2)out.println(threeNoded1 + " " + threeNoded2 + " " + threeNoded3); else{ int num = M / 4; String g = threeNoded1 + " " + threeNoded2 + " " + threeNoded3 + " " + threeNoded2 + " "; for(int i = 0; i<num; i++)out.print(g); out.println(threeNoded1 + " " + threeNoded2 + " " + threeNoded3); } } } } out.flush(); } //Find same on top and bottom //Find same on side to side static class Node{ int a_connect = -1; int b_connect = -1; } 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()); } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
ec96a29f0b1f168a11a588956663c05b
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; public class N699 { static PrintWriter out; static Scanner sc; static ArrayList<Integer>primes; static HashSet<Integer>primesH; static boolean prime[]; //static ArrayList<Integer>a; static HashSet<Long>h; static int[][]v; static int[]a,b,c,oa,oc; static HashSet<Integer>[]ob; static int[][]mp; static long[]l; static int mx; public static void main(String[]args) throws IOException { sc=new Scanner(System.in); out=new PrintWriter(System.out); //A(); //sieveOfEratosthenes(1000000); //B(); //C(); //minimum for subarrays of fixed length D(); out.close(); } private static void A() throws IOException { int t=sc.nextInt(); while(t-->0) { int px=sc.nextInt(),py=sc.nextInt(); int r=0,u=0,d=0,l=0; String s=sc.next(); for(int i=0;i<s.length();i++) { switch(s.charAt(i)) { case 'U':u++;break; case'R':r++;break; case 'D':d++;break; case'L':l++;break; } } int x=r-l,y=u-d; boolean a=px-x<=l&&px>=x; boolean b=py-y<=d&&py>=y; boolean c=x-px<=r&&px<=x; boolean e=y-py<=u&&py<=y; if(px==x&&py==y||a&&b||a&&e||c&&b||c&&e) { out.println("YES"); }else { out.println("NO"); } } } static void B() throws IOException { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),k=sc.nextInt(); a=sc.nextArrInt(n); int pos=-1; int i=0; for(;i<n-1;i++) { if(a[i]>=a[i+1])continue; k--; a[i]++; if(k<=0)break; i-=2; if(i<-1) { i=-1; } } out.println(i==n-1?-1:i+1); } } static void C() throws IOException { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),m=sc.nextInt(); a=sc.nextArrInt(n); b=sc.nextArrInt(n); c=sc.nextArrInt(m); ob=new HashSet[n+1]; int[]ans=new int[m]; // ob=new int[n+1]; // oc=new int[n+1]; for(int i=0;i<=n;i++) { ob[i]=new HashSet<Integer>(); } for(int i=0;i<n;i++) { if(a[i]!=b[i]) ob[b[i]].add(i); } HashSet<Integer>last=ob[c[m-1]]; int pos=getElement(last); if(pos==-1) { int g=c[m-1]; for(int i=n-1;i>=0;i--) { if(b[i]==g) { pos=i; break; } } }else { ob[c[m-1]].remove(pos); } if(pos==-1) { //noooo out.println("NO"); }else { ans[m-1]=pos; for(int i=0;i<m-1;i++) { int p=getElement(ob[c[i]]); if(p==-1) { ans[i]=pos; }else { ans[i]=p; ob[c[i]].remove(p); } } boolean f=true; for(HashSet<Integer>j:ob) { if(j.size()!=0) { f=false; break; } } if(f) { out.println("YES"); for(int i=0;i<m;i++) { out.print((ans[i]+1)+" "); } out.println(); }else { out.println("NO"); } } } } static int getElement(HashSet<Integer>k) { for(int e:k) { return e; } return -1; } static void D() throws IOException { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),m=sc.nextInt(); mp=new int[n][n]; v=new int[n][2]; for(int i=0;i<n;i++)Arrays.fill(v[i], -1); for(int i=0;i<n;i++) { String s=sc.next(); for(int j=0;j<n;j++) { mp[i][j]=i==j?-1:s.charAt(j)-'a'; if(i==j)continue; v[i][s.charAt(j)-'a']=j; } } boolean f=false;int v1=0,v2=1; //int h=(int) Math.floor((n-1)/2); for(int i=0;i<n&&!f;i++) { for(int j=0;j<n&&!f;j++) { if(j==i)continue; if(mp[i][j]==mp[j][i]) { f=true; v1=i;v2=j; } } } if(f||m%2==1) { //ok boolean hi=false; out.println("YES"); for(int i=0;i<=m;i++) { out.print((hi?(v1+1):(v2+1))+" "); hi=!hi; } out.println(); }else { boolean k=false; for(int i=0;i<n&&!k;i++) { for(int j=0;j<n&&!k;j++) { if(i==j)continue; if(v[j][mp[i][j]]==-1)continue; k=true; out.println("YES"); int cur=v[j][mp[i][j]]; if((m/2)%2==0) { out.print(j+1); for(int jj=0;jj<m/2;jj++) { if(jj%2==1) { out.print(" "+(j+1)); }else { out.print(" "+(cur+1)); } } for(int jj=0;jj<m/2;jj++) { if(jj%2==1) { out.print(" "+(j+1)); }else { out.print(" "+(i+1)); } } }else { for(int jj=0;jj<m+1;jj++) { if(jj%2==1) { out.print((j+1)+" "); }else if(jj%4==0) { out.print((i+1)+" "); }else { out.print((cur+1)+" "); } } //out.print(j+1); } out.println(); } } if(!k) { out.println("NO"); } } } } // Math.floor((n-1)/2); private static int solve(int i, int j) { int x=i,y=j; int max=0; for(int t=0;t<mp.length;t++) { } return 0; } static class Pair{ int a,min; Pair(int a,int min){ this.a=a; this.min=min; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public boolean hasNext() {return st.hasMoreTokens();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready(); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static void sieveOfEratosthenes(int n) // O(n*log(log(n))) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. prime = new boolean[n+1]; for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[p] == true) { // Update all multiples of p for(int i = p*p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(int i = 2; i <= n; i++) { if(prime[i] == true) { //System.out.print(i + " "); //primes.add(i); //primesH.add(i); } } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
4ca79343e7b691006aba63cd24366eb9
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
// Don't place your source in a package import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner {//scanner from SecondThread BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int T=Int(); for(int t=0;t<T;t++){ int n=Int();int m=Int(); char A[][]=new char[n][n]; for(int i=0;i<n;i++){ String s=Str(); A[i]=s.toCharArray(); } Solution sol=new Solution(); sol.solution(out,A,m); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ public void solution(PrintWriter out,char A[][],int m){ int n=A.length; for(int i=0;i<A.length;i++){//basic check for(int j=0;j<A.length;j++){ if(i==j)continue; if(A[i][j]==A[j][i]||m%2==1){ out.println("YES"); for(int k=0;k<=m;k++){ if(k%2==0){ out.print((i+1)+" "); } else{ out.print((j+1)+" "); } } out.println(); return; } } } //preprocessing boolean check[]=new boolean[n]; for(int i=0;i<n;i++){ Set<Character>set=new HashSet<>(); for(int j=0;j<n;j++){ if(i==j)continue; set.add(A[i][j]); } if(set.size()==2)check[i]=true; } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j)continue; if(m==2&&check[j]){//special case int k=-1; for(int x=0;x<n;x++){ if(A[i][j]==A[j][x])k=x; } if(k!=-1){ out.println("YES"); out.print((i+1)+" "); out.print((j+1)+" "); out.print((k+1)+" "); out.println(); return; } } if(m%4==0){ if(check[i]){ int k=-1; for(int x=0;x<n;x++){ if(A[i][x]==A[j][i])k=x; } if(k==-1)continue; out.println("YES"); for(int x=0;x<=m/2;x++){ if(x%2==0){ out.print((i+1)+" "); } else{ out.print((j+1)+" "); } } for(int x=0;x<m/2;x++){ if(x%2==0){ out.print((k+1)+" "); } else{ out.print((i+1)+" "); } } out.println(); return; } } else{ if(check[j]){ int k=-1; for(int x=0;x<n;x++){ if(A[j][x]==A[i][j])k=x; } if(k==-1)continue; out.println("YES"); for(int x=0;x<=m/2;x++){ if(x%2==0){ out.print((i+1)+" "); } else{ out.print((j+1)+" "); } } for(int x=0;x<m/2;x++){ if(x%2==0){ out.print((k+1)+" "); } else{ out.print((j+1)+" "); } } out.println(); return; } } } } // out.println("NO"); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
c2ec59cc4f68519cd46951fb6246d9b4
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import javax.print.DocFlavor; import java.util.*; import java.io.*; import java.awt.*; public class ABGraph { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(f.readLine()); for (int z = 0; z<t; z++) { StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] e = new int[n+1][n+1]; int[] a = new int[n+1]; int[] b = new int[n+1]; int aneg = -1; int bneg = -1; for (int i=1; i<=n; i++) { String str = f.readLine(); for (int j=1; j<=n; j++) { if (str.charAt(j-1)=='a') { e[i][j] = 1; } else if (str.charAt(j-1)=='b') { e[i][j] = 2; a[i] = j; b[j] = i; } } } int first = -1; int second = -1; for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { if (i!=j && e[i][j]==e[j][i]) { first = i; second = j; } } } if (first==-1 && second==-1) { if (m%2==1) { out.println("YES"); for (int i=0; i<=m; i++) { if (i%2==0) out.print(1 + " "); else out.print(2 + " "); } out.println(); } else { int ind = 0; for (int i = 1; i <=n; i++) { if (b[i] != 0 && a[i] != 0) { ind = i; } } if (ind==0) { out.println("NO"); } else { out.println("YES"); int x = m / 2; if (x % 2 == 0) { for (int i = 0; i < x; i++) { if (i % 2 == 0) out.print(ind + " "); else out.print(b[ind] + " "); } out.print(ind + " "); for (int i = 0; i < x; i++) { if (i % 2 == 0) out.print(a[ind] + " "); else out.print(ind + " "); } } else { for (int i = 1; i <= x; i++) { if (i % 2 == 0) out.print(ind + " "); else out.print(b[ind] + " "); } out.print(ind + " "); for (int i = 0; i < x; i++) { if (i % 2 == 0) out.print(a[ind] + " "); else out.print(ind + " "); } } out.println(); } } } else { out.println("YES"); for (int i=0; i<=m; i++) { if (i%2==0) out.print(first + " "); else out.print(second + " "); } out.println(); } } out.close(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
38ccc577d0e9af4bcec438b6871bdc6c
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class MainClass { public static void main(String[] args) { Reader in = new Reader(System.in); int t = in.nextInt(); StringBuilder stringBuilder = new StringBuilder(); while (t-- > 0) { int n = in.nextInt(), m = in.nextInt(); char[][] S = new char[n][n]; for (int i = 0; i < n;i++) S[i] = in.next().toCharArray(); if (m == 1) { stringBuilder.append("YES\n1 2\n"); continue; } if (n == 2 && S[0][1] != S[1][0] && m % 2 == 0) { stringBuilder.append("NO\n"); continue; } if (n == 2) { if (m % 2 == 1) { stringBuilder.append("YES\n"); stringBuilder.append(1).append(" "); for (int i=0;i<m;i++) { if (i % 2 == 0) stringBuilder.append(2).append(" "); else stringBuilder.append(1).append(" "); } stringBuilder.append("\n"); continue; } } boolean ff = false; int idx1 = -1; int idx2 =-1; if (m % 2 == 1) { stringBuilder.append("YES\n"); stringBuilder.append(1).append(" "); for (int i=0;i<m;i++) { if (i % 2 == 0) stringBuilder.append(2).append(" "); else stringBuilder.append(1).append(" "); } stringBuilder.append("\n"); continue; } for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (i == j) continue; else if (S[i][j] == S[j][i]) { ff = true; idx1 = i; idx2 = j; break; } } } if (ff) { stringBuilder.append("YES\n"); for (int i=0;i<=m;i++) { if (i % 2 == 0) stringBuilder.append(idx1 + 1).append(" "); else stringBuilder.append(idx2 + 1).append(" "); } stringBuilder.append("\n"); continue; } if (S[0][1] == S[1][2]) { //1 2 3 stringBuilder.append("YES\n"); if ((m / 2) % 2 == 1) { stringBuilder.append("1 "); for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(2).append(" "); else stringBuilder.append(1).append(" "); } for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(3).append(" "); else stringBuilder.append(2).append(" "); } } else { stringBuilder.append("2 "); for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(3).append(" "); else stringBuilder.append(2).append(" "); } for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(1).append(" "); else stringBuilder.append(2).append(" "); } } stringBuilder.append("\n"); } else if (S[1][0] == S[0][2]) { //2 - 1 - 3 stringBuilder.append("YES\n"); if ((m / 2) % 2 == 1) { stringBuilder.append("2 "); for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(1).append(" "); else stringBuilder.append(2).append(" "); } for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(3).append(" "); else stringBuilder.append(1).append(" "); } } else { stringBuilder.append("1 "); for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(3).append(" "); else stringBuilder.append(1).append(" "); } for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(2).append(" "); else stringBuilder.append(1).append(" "); } } stringBuilder.append("\n"); } else { //1 - 3 - 2 stringBuilder.append("YES\n"); if ((m / 2) % 2 == 1) { stringBuilder.append("1 "); for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(3).append(" "); else stringBuilder.append(1).append(" "); } for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(2).append(" "); else stringBuilder.append(3).append(" "); } } else { stringBuilder.append("3 "); for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(2).append(" "); else stringBuilder.append(3).append(" "); } for (int i=0;i<m / 2;i++) { if (i % 2 == 0) stringBuilder.append(1).append(" "); else stringBuilder.append(3).append(" "); } } stringBuilder.append("\n"); } } System.out.println(stringBuilder); } } class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader(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\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
e7672fdfcc254dda1fd8e73fcecadd3b
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class D_AB_Graph{ public static void main(String[] args) { FastScanner s= new FastScanner(); //PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; // int alpha=0; while(p<t){ int n=s.nextInt(); int m=s.nextInt(); char matrix[][]= new char[n][n]; for(int i=0;i<n;i++){ String str=s.nextToken(); for(int j=0;j<n;j++){ matrix[i][j]=str.charAt(j); } } // if(t==320 && p==0 && m==6){ // alpha=1; // } // if(p==55 && alpha==1){ // System.out.println("n "+n); // System.out.println("m "+m); // for(int i=0;i<n;i++){ // for(int j=0;j<n;j++){ // System.out.print(matrix[i][j]); // } // System.out.println(); // } // } int node1=-1; int node2=-1; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ continue; } char ch1=matrix[i][j]; char ch2=matrix[j][i]; if(ch1==ch2){ node1=i; node2=j; break; } } if(node1!=-1){ break; } } if(node1!=-1){ // int hh=0; res.append("YES \n"); node1++; node2++; for(int i=0;i<m+1;i++){ if(i%2==0){ res.append(node1+" "); } else{ res.append(node2+" "); } } } else{ if(m%2!=0){ res.append("YES \n"); node1=1; node2=2; for(int i=0;i<m+1;i++){ if(i%2==0){ res.append(node1+" "); } else{ res.append(node2+" "); } } } else{ //m is even node1=-1; node2=-1; int node3=-1; int check=0; for(int i=0;i<n;i++){ int a=0; int b=0; for(int j=0;j<n;j++){ if(i==j){ continue; } char ch=matrix[i][j]; if(ch=='a'){ a++; } else{ b++; } } if(a!=0 && b!=0){ check=1; node1=i; for(int j=0;j<n;j++){ if(i==j){ continue; } char ch=matrix[i][j]; if(ch=='a'){ node2=j; break; } } for(int j=0;j<n;j++){ if(i==j){ continue; } char ch=matrix[i][j]; if(ch=='b'){ node3=j; break; } } } if(check==1){ break; } } if(check==1){ //answer exists if(m>2){ if((m/2)%2==0){ res.append("YES \n"); node1++; node2++; node3++; int half=m/2; for(int i=0;i<half;i++){ if(i%2==0){ res.append(node1+" "); } else{ res.append(node2+" "); } } for(int i=0;i<half;i++){ if(i%2==0){ res.append(node1+" "); } else{ res.append(node3+" "); } } res.append(node1+" "); } else{ int a[]= new int[n]; int b[]= new int[n]; for(int i=0;i<n;i++){ int alph=0; int beta=0; for(int j=0;j<n;j++){ if(i==j){ continue; } if(matrix[i][j]=='a'){ alph++; } else{ beta++; } } a[i]=alph; b[i]=beta; } node1=-1; node2=-1; node3=-1; int check2=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ continue; } if(matrix[i][j]=='a'){ if(a[j]>0){ check2=1; node1=i; node2=j; for(int k=0;k<n;k++){ if(j==k){ continue; } if(matrix[j][k]=='a'){ node3=k; break; } } break; } } else{ if(b[j]>0){ check2=1; node1=i; node2=j; for(int k=0;k<n;k++){ if(j==k){ continue; } if(matrix[j][k]=='b'){ node3=k; break; } } break; } } } if(check2==1){ break; } } if(check2==1){ res.append("YES \n"); node1++; node2++; node3++; int half=m/2; for(int i=0;i<half;i++){ if(i%2==0){ res.append(node1+" "); } else{ res.append(node2+" "); } } for(int i=0;i<half;i++){ if(i%2==0){ res.append(node2+" "); } else{ res.append(node3+" "); } } res.append(node3+" "); res.append(" \n"); } else{ res.append("NO \n"); } } } else{ //m==2 int a[]= new int[n]; int b[]= new int[n]; for(int i=0;i<n;i++){ int alph=0; int beta=0; for(int j=0;j<n;j++){ if(i==j){ continue; } if(matrix[i][j]=='a'){ alph++; } else{ beta++; } } a[i]=alph; b[i]=beta; } node1=-1; node2=-1; node3=-1; int check2=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ continue; } if(matrix[i][j]=='a'){ if(a[j]>0){ check2=1; node1=i; node2=j; for(int k=0;k<n;k++){ if(j==k){ continue; } if(matrix[j][k]=='a'){ node3=k; break; } } break; } } else{ if(b[j]>0){ check2=1; node1=i; node2=j; for(int k=0;k<n;k++){ if(j==k){ continue; } if(matrix[j][k]=='b'){ node3=k; break; } } break; } } } if(check2==1){ break; } } if(check2==1){ node1++; node2++; node3++; res.append("YES \n"); res.append(node1+" "+node2+" "+node3+" \n"); } else{ res.append("NO \n"); } } } else{ res.append("NO \n"); } } } res.append(" \n"); p++;} // if(alpha==0) System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
059074f180f7cf3708fd44814f990e71
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
/******************************************************************************* * author : dante1 * created : 05/02/2021 21:47 *******************************************************************************/ import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // import java.math.BigInteger; import java.util.*; public class d { public static void main(String[] args) { int T = in.nextInt(); TEST: while (T-- > 0) { int n = in.nextInt(), m = in.nextInt(); char[][] graph = new char[n][n]; for (int i = 0; i < n; i++) { graph[i] = in.next().toCharArray(); } if ((m & 1) == 1) { printPath(0, 1, -1, m); continue TEST; } Integer[] aind = new Integer[n]; Integer[] bind = new Integer[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { continue; } if (graph[i][j] == graph[j][i]) { printPath(i, j, -1, m); continue TEST; } else if (graph[j][i] == 'a' && aind[j] != null) { printPath(aind[j], j, i, m); continue TEST; } else if (graph[j][i] == 'b' && bind[j] != null) { printPath(bind[j], j, i, m); continue TEST; } else if (graph[i][j] == 'a') { aind[j] = i; } else { bind[j] = i; } } } out.println("NO"); } out.flush(); } static void printPath(int i, int j, int k, int m) { out.println("YES"); int state = ((m & 1) == 1) ? 0 : ((m/2 & 1) == 1) ? 0 : 1; boolean flag = false; for (int l = 0; l <= m; l++) { if (state == 0) { out.print((i+1) + " "); state = 1; } else if (state == 1) { out.print((j+1) + " "); state = (k == -1) ? 0 : (flag) ? 0 : 2; flag = false; } else { out.print((k+1) + " "); flag = true; state = 1; } } out.println(); } // Handle I/O static int MOD = (int) (1e9 + 7); static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = nextInt(); } return arr; } long nextLong() { return Long.parseLong(next()); } long[] readLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; i++) { arr[i] = nextLong(); } return arr; } double nextDouble() { return Double.parseDouble(next()); } double[] readDoubleArray(int size) { double[] arr = new double[size]; for (int i = 0; i < size; i++) { arr[i] = nextDouble(); } return arr; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
acf0890666478f710c9cd6306dd60d32
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
/******************************************************************************* * author : dante1 * created : 05/02/2021 21:47 *******************************************************************************/ import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // import java.math.BigInteger; import java.util.*; public class d { public static void main(String[] args) { int T = in.nextInt(); TEST: while (T-- > 0) { int n = in.nextInt(), m = in.nextInt(); char[][] graph = new char[n][n]; for (int i = 0; i < n; i++) { graph[i] = in.next().toCharArray(); } if ((m & 1) == 1) { printPath(0, 1, m); continue TEST; } Integer[] aind = new Integer[n]; Integer[] bind = new Integer[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { continue; } if (graph[i][j] == graph[j][i]) { printPath(i, j, m); continue TEST; } else if (graph[j][i] == 'a' && aind[j] != null) { printPath(aind[j], j, i, m); continue TEST; } else if (graph[j][i] == 'b' && bind[j] != null) { printPath(bind[j], j, i, m); continue TEST; } else if (graph[i][j] == 'a') { aind[j] = i; } else { bind[j] = i; } } } out.println("NO"); } out.flush(); } static void printPath(int i, int j, int m) { out.println("YES"); boolean flag = true; for (int k = 0; k <= m; k++, flag = !flag) { if (flag) { out.print((i+1) + " "); } else { out.print((j+1) + " "); } } out.println(); } static void printPath(int i, int j, int k, int m) { out.println("YES"); int state = ((m/2 & 1) == 1)? 0 : 1; boolean flag = false; for (int l = 0; l <= m; l++) { if (state == 0) { out.print((i+1) + " "); state = 1; } else if (state == 1) { out.print((j+1) + " "); state = (flag)? 0 : 2; flag = false; } else { out.print((k+1) + " "); flag = true; state = 1; } } out.println(); } // Handle I/O static int MOD = (int) (1e9 + 7); static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = nextInt(); } return arr; } long nextLong() { return Long.parseLong(next()); } long[] readLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; i++) { arr[i] = nextLong(); } return arr; } double nextDouble() { return Double.parseDouble(next()); } double[] readDoubleArray(int size) { double[] arr = new double[size]; for (int i = 0; i < size; i++) { arr[i] = nextDouble(); } return arr; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
d22052b7a3654d53a9c7a4b34cc9dc4f
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { int n, m, k; static boolean use_n_tests = true; void solve(FastScanner in, PrintWriter out, int testNumber) { n = in.nextInt(); m = in.nextInt(); char[][] s = new char[n][]; for (int i = 0; i < n; i++) { s[i] = in.next().toCharArray(); } int sr = -1, ds = -1; int sr1 = -1, tr = -1, en = -1; int[][] in1 = new int[n][2]; int[][] out1 = new int[n][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { continue; } if (s[i][j] == s[j][i]) { sr = i; ds = j; } in1[i][s[j][i] - 'a'] = j + 1; out1[i][s[i][j] - 'a'] = j + 1; } } for (int i = 0; i < n; i++) { if (in1[i][0] != 0 && out1[i][0] != 0) { sr1 = in1[i][0] - 1; tr = i; en = out1[i][0] - 1; break; } if (in1[i][1] != 0 && out1[i][1] != 0) { sr1 = in1[i][1] - 1; tr = i; en = out1[i][1] - 1; break; } } if (sr != -1) { out.println("YES"); print(m, sr, ds); return; } if (m % 2 == 1) { out.println("YES"); print(m, 0, 1); } else { if (sr1 != -1) { out.println("YES"); int m2 = m / 2; if (m2 % 2 == 1) { for (int i = 0; i < m2; i++) { if (i % 2 == 0) { out.printf("%d %d %d ", sr1 + 1, tr + 1, en + 1); } else { out.printf("%d ", tr + 1); } } } else { for (int i = 0; i < m2; i++) { if (i % 2 == 0) { out.printf("%d %d %d ", tr + 1, en + 1, tr + 1); } else { out.printf("%d ", sr1 + 1); } } out.printf("%d\n", tr + 1); } } else { out.println("NO"); } } } void print(int m, int s, int d) { s++; d++; out.print(s + " "); for (int i = 0; i < m; i++) { if (i % 2 == 0) { out.print(d + " "); } else { out.print(s + " "); } } out.println(); } // ****************************** template code *********** static int stack_size = 1 << 27; void pre_solve() { } class Coeff { long mod; long[][] C; long[] fact; boolean cycleWay = false; Coeff(int n, long mod) { this.mod = mod; fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = i; fact[i] %= mod; fact[i] *= fact[i - 1]; fact[i] %= mod; } } Coeff(int n, int m, long mod) { // n > m cycleWay = true; this.mod = mod; C = new long[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, m); j++) { if (j == 0 || j == i) { C[i][j] = 1; } else { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; C[i][j] %= mod; } } } } public long C(int n, int m) { if (cycleWay) { return C[n][m]; } return fC(n, m); } private long fC(int n, int m) { return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod; } private long inv(long r) { if (r == 1) return 1; return ((mod - mod / r) * inv(mod % r)) % mod; } } class Pair { int first; int second; public int getFirst() { return first; } public int getSecond() { return second; } } class MultisetTree<T> { int size = 0; TreeMap<T, Integer> mp = new TreeMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } boolean contains(T x) { return mp.containsKey(x); } T greatest() { return mp.lastKey(); } T smallest() { return mp.firstKey(); } int size() { return size; } int diffSize() { return mp.size(); } void clear() { mp.clear(); size = 0; } } class Multiset<T> { int size = 0; Map<T, Integer> mp = new HashMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } boolean contains(T x) { return mp.containsKey(x); } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } int size() { return size; } int diffSize() { return mp.size(); } } static class Range { int l, r; int id; public int getL() { return l; } public int getR() { return r; } public Range(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } static class Array { static Range[] readRanges(int n, FastScanner in) { Range[] result = new Range[n]; for (int i = 0; i < n; i++) { result[i] = new Range(in.nextInt(), in.nextInt(), i); } return result; } static boolean isSorted(Integer[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static public <T> long sum(T[] a) { long sum = 0; for (T x : a) { if (x instanceof Integer) { sum += (Integer) x; } else { sum += (Long) x; } } return sum; } static public int min(Integer[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int min(int[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int max(Integer[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int max(int[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int[] readint(int n, FastScanner in) { int[] out = new int[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } } class Graph { List<List<Integer>> graph; Graph(int n) { create(n); } void create(int n) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } this.graph = graph; } void readBi(int m, FastScanner in) { for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; graph.get(v).add(u); graph.get(u).add(v); } } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String line() { String result = ""; try { result = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return result; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long[] nextArrayL(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Long[] nextArrayL2(int n) { Long[] res = new Long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Integer[] nextArray2(int n) { Integer[] res = new Integer[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long nextLong() { return Long.parseLong(next()); } } void run_t_tests() { pre_solve(); int t = in.nextInt(); int i = 0; while (t-- > 0) { solve(in, out, i++); } } void run_one() { solve(in, out, -1); } @Override public void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); if (use_n_tests) { run_t_tests(); } else { run_one(); } out.close(); } static FastScanner in; static PrintWriter out; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(null, new Main(), "", stack_size); thread.start(); thread.join(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
e2cd8a828e5181e7ca9f4cf594e07619
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*;import java.util.*;import java.math.*; public class Main { static long mod=1000000007l; static int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE; static long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE; static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static StringBuilder sb; static public void main(String[] args)throws Exception { st=new StringTokenizer(br.readLine()); int t=i(); sb=new StringBuilder(1000000); o: while(t-->0) { int n=i(); int m=i()+1; char ar[][]=arc(n,n); if((m&1)==0) { int a[]=new int[m]; for(int x=0;x<m;x+=2)a[x]=1; for(int x=1;x<m;x+=2)a[x]=2; sl("YES"); s(a); } else { for(int x=0;x<n;x++) { for(int y=x+1;y<n;y++) { if(ar[x][y]==ar[y][x]) { int a[]=new int[m]; for(int xa=0;xa<m;xa+=2)a[xa]=x+1; for(int xa=1;xa<m;xa+=2)a[xa]=y+1; sl("YES"); s(a); continue o; } } } if(n==2) { if(ar[0][1]==ar[1][0]) { int a[]=new int[m]; for(int x=0;x<m;x+=2)a[x]=1; for(int x=1;x<m;x+=2)a[x]=2; sl("YES"); s(a); } else { sl("NO"); } } else { int aa[]=new int[]{ar[0][1],ar[1][2],ar[2][0]}; int nn=10+m; int q[]=new int[nn]; int p=0; for(int x=0;x<nn;x++) { q[x]=p; p=(p+1)%3; } oo: for(int x=0;x<3;x++) { int f=x+m-1; int i=x; int j=f-1; int s=x; while(i<j) { if(aa[q[i]]!=aa[q[j]])continue oo; i++; j--; } int a[]=new int[m]; int ii=-1; while(m-->0) { a[++ii]=s+1; s=(s+1)%3; } sl("YES"); s(a); break; } } } } p(sb); } static int[] so(int ar[]) { Integer r[]=new Integer[ar.length]; for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r); for(int x=0;x<ar.length;x++)ar[x]=r[x]; return ar; } static long[] so(long ar[]) { Long r[]=new Long[ar.length]; for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r); for(int x=0;x<ar.length;x++)ar[x]=r[x]; return ar; } static char[] so(char ar[]) { Character r[]=new Character[ar.length]; for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r); for(int x=0;x<ar.length;x++)ar[x]=r[x]; return ar; } static void s(String s){sb.append(s);} static void s(int s){sb.append(s);} static void s(long s){sb.append(s);} static void s(char s){sb.append(s);} static void s(double s){sb.append(s);} static void ss(){sb.append(' ');} static void sl(String s){sb.append(s);sb.append("\n");} static void sl(int s){sb.append(s);sb.append("\n");} static void sl(long s){sb.append(s);sb.append("\n");} static void sl(char s){sb.append(s);sb.append("\n");} static void sl(double s){sb.append(s);sb.append("\n");} static void sl(){sb.append("\n");} static int max(int ...a){int m=a[0];for(int e:a)m=(m>=e)?m:e;return m;} static int min(int ...a){int m=a[0];for(int e:a)m=(m<=e)?m:e;return m;} static int abs(int a){return Math.abs(a);} static long max(long ...a){long m=a[0];for(long e:a)m=(m>=e)?m:e;return m;} static long min(long ...a){long m=a[0];for(long e:a)m=(m<=e)?m:e;return m;} static long abs(long a){return Math.abs(a);} static int sq(int a){return (int)Math.sqrt(a);} static long sq(long a){return (long)Math.sqrt(a);} static long gcd(long a,long b){return b==0l?a:gcd(b,a%b);} static boolean pa(String s,int i,int j) { while(i<j)if(s.charAt(i++)!=s.charAt(j--))return false; return true; } static int ncr(int n,int c,long m) { long a=1l; for(int x=n-c+1;x<=n;x++)a=((a*x)%m); long b=1l; for(int x=2;x<=c;x++)b=((b*x)%m); return (int)((a*(mul((int)b,m-2,m)%m))%m); } static boolean[] si(int n) { boolean bo[]=new boolean[n+1]; bo[0]=true;bo[1]=true; for(int x=4;x<=n;x+=2)bo[x]=true; for(int x=3;x*x<=n;x+=2) { if(!bo[x]) { int vv=(x<<1); for(int y=x*x;y<=n;y+=vv)bo[y]=true; } } return bo; } static int[] fac(int n) { int bo[]=new int[n+1]; for(int x=1;x<=n;x++)for(int y=x;y<=n;y+=x)bo[y]++; return bo; } static long mul(long a,long b,long m) { long r=1l; a%=m; while(b>0) { if((b&1)==1)r=(r*a)%m; b>>=1; a=(a*a)%m; } return r; } static int i()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } static long l()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } static String s()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return st.nextToken(); } static double d()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return Double.parseDouble(st.nextToken()); } static void p(Object p){System.out.print(p);} static void p(String p){System.out.print(p);} static void p(int p){System.out.print(p);} static void p(double p){System.out.print(p);} static void p(long p){System.out.print(p);} static void p(char p){System.out.print(p);} static void p(boolean p){System.out.print(p);} static void pl(Object p){System.out.println(p);} static void pl(String p){System.out.println(p);} static void pl(int p){System.out.println(p);} static void pl(char p){System.out.println(p);} static void pl(double p){System.out.println(p);} static void pl(long p){System.out.println(p);} static void pl(boolean p){System.out.println(p);} static void pl(){System.out.println();} static void s(int a[]) { for(int e:a) { sb.append(e); sb.append(' '); } sb.append("\n"); } static void s(long a[]) { for(long e:a) { sb.append(e); sb.append(' '); } sb.append("\n"); } static void s(int ar[][]) { for(int a[]:ar) { for(int e:a) { sb.append(e); sb.append(' '); } sb.append("\n"); } } static void s(char a[]) { for(char e:a) { sb.append(e); sb.append(' '); } sb.append("\n"); } static void s(char ar[][]) { for(char a[]:ar) { for(char e:a) { sb.append(e); sb.append(' '); } sb.append("\n"); } } static int[] ari(int n)throws IOException { int ar[]=new int[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++)ar[x]=Integer.parseInt(st.nextToken()); return ar; } static int[][] ari(int n,int m)throws IOException { int ar[][]=new int[n][m]; for(int x=0;x<n;x++) { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken()); } return ar; } static long[] arl(int n)throws IOException { long ar[]=new long[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++) ar[x]=Long.parseLong(st.nextToken()); return ar; } static long[][] arl(int n,int m)throws IOException { long ar[][]=new long[n][m]; for(int x=0;x<n;x++) { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken()); } return ar; } static String[] ars(int n)throws IOException { String ar[]=new String[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++) ar[x]=st.nextToken(); return ar; } static double[] ard(int n)throws IOException { double ar[]=new double[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken()); return ar; } static double[][] ard(int n,int m)throws IOException { double ar[][]=new double[n][m]; for(int x=0;x<n;x++) { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int y=0;y<m;y++)ar[x][y]=Double.parseDouble(st.nextToken()); } return ar; } static char[] arc(int n)throws IOException { char ar[]=new char[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0); return ar; } static char[][] arc(int n,int m)throws IOException { char ar[][]=new char[n][m]; for(int x=0;x<n;x++) { String s=br.readLine(); for(int y=0;y<m;y++)ar[x][y]=s.charAt(y); } return ar; } static void p(int ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(int a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(int ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(int a[]:ar) { for(int aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } static void p(long ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(long a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(long ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(long a[]:ar) { for(long aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } static void p(String ar[]) { int c=0; for(String s:ar)c+=s.length()+1; StringBuilder sb=new StringBuilder(c); for(String a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(double ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(double a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(double ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(double a[]:ar) { for(double aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } static void p(char ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(char aa:ar) { sb.append(aa); sb.append(' '); } System.out.println(sb); } static void p(char ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(char a[]:ar) { for(char aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
389863ae3d6661d02f65f8df4b5b915e
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
// No sorcery shall prevail. // import java.util.*; import java.io.*; public class _InVoker_ { //Variables static long mod = 1000000007; static long mod2 = 998244353; static FastReader inp= new FastReader(); static PrintWriter out= new PrintWriter(System.out); public static void main(String args[]) { _InVoker_ g=new _InVoker_(); g.main(); out.close(); } //Main void main() { int tt=inp.nextInt(); loop: while(tt-->0) { int n=inp.nextInt(); int m=inp.nextInt(); char a[][]=new char[n][n]; for(int i=0;i<n;i++) a[i]=inp.next().toCharArray(); if(m%2==1) { out.println("YES"); for(int i=0;i<=m;i++) out.print((i%2 +1)+" "); out.println(); continue loop; } int A[]=new int[n]; int B[]=new int[n]; Arrays.fill(A, -1); Arrays.fill(B, -1); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) continue; if(a[i][j]==a[j][i]) { out.println("YES"); for(int k=0;k<=m;k++) { out.print((k%2==0?i+1:j+1)+" "); } out.println(); continue loop; } if(a[i][j]=='a') A[i]=j; else B[i]=j; } } for(int i=0;i<n;i++) { if(A[i]!=-1 && B[i]!=-1) { out.println("YES"); if(m%4==0) { out.print((i+1)+" "); for(int k=0;k<m/2;k++) { out.print((k%2==1?i+1:A[i]+1)+" "); } for(int k=0;k<m/2;k++) { out.print((k%2==1?i+1:B[i]+1)+" "); } out.println(); }else { out.print((A[i]+1)+" "); for(int k=0;k<m/2;k++) { out.print((k%2==0?i+1:A[i]+1)+" "); } for(int k=0;k<m/2;k++) { out.print((k%2==1?i+1:B[i]+1)+" "); } out.println(); } continue loop; } } out.println("NO"); } } /********************************************************************************************************************************************************************************************************* * ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE* *ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE * *ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE * *ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE * *ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE * *ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE * *ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD * *ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE * *ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD * *ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD * *ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD * *ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD * *ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD * *ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD * *ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD * *tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD * *tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE * *ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD * *tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD * *ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD * *tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD * *ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD * *tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD * *tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD * *tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD * *tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD * *tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD * *tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD * *tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD * *tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD * *tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD * *tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD * *tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD * *tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD * *jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD * *tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD * *tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD * *jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD * *jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD * *jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD * *jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD * *jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD * *jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD * *jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD * *jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD * *jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD * *jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD * *jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD * *jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD * *jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD * *jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD * *jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD * *jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD * *jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD * *jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED * *jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE * *jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD * *jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG * *jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG * *jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG * *jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG * *jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG * *fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL * *fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL * *fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL * *fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG * *fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG * *fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG * *fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG * *fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD * *jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD * *fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD * *fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD * *fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD * *fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD * *fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD * *jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD * *fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG * *fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; * *fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, * *fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, * *fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, * *fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; * ***********************************************************************************************************************************************************************************************************/ void sort(int a[]) { ArrayList<Integer> list=new ArrayList<>(); for(int x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void sort(long a[]) { ArrayList<Long> list=new ArrayList<>(); for(long x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void ruffleSort(int a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); int temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(a); } void ruffleSort(long a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); long temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(a); } 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 s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } long fact[]; long invFact[]; void init(int n) { fact=new long[n+1]; invFact=new long[n+1]; fact[0]=1; for(int i=1;i<=n;i++) { fact[i]=mul(i,fact[i-1]); } invFact[n]=power(fact[n],mod-2); for(int i=n-1;i>=0;i--) { invFact[i]=mul(invFact[i+1],i+1); } } long modInv(long x) { return power(x,mod-2); } long nCr(int n, int r) { if(n<r || r<0) return 0; return mul(fact[n],mul(invFact[r],invFact[n-r])); } long mul(long a, long b) { return a*b%mod; } long add(long a, long b) { return (a+b)%mod; } long power(long x, long y) { long gg=1; while(y>0) { if(y%2==1) gg=mul(gg,x); x=mul(x,x); y/=2; } return gg; } // Functions static long gcd(long a, long b) { return b==0?a:gcd(b,a%b); } static int gcd(int a, int b) { return b==0?a:gcd(b,a%b); } void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); out.println(); } void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); out.println(); } //Input Arrays static void input(long a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextLong(); } } static void input(int a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextInt(); } } static void input(String s[],int n) { for(int i=0;i<n;i++) { s[i]=inp.next(); } } static void input(int a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextInt(); } } } static void input(long a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextLong(); } } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
2a22f61b22d7ae418d801e688a3b1995
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class D { public void solve() { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(), m = in.nextInt(); int a[][] = new int[n][n]; for (int i = 0; i<n; i++) { char [] line = in.next().toCharArray(); for (int j = 0; j<n; j++) if (line[j] != '*') a[i][j] = line[j] - 'a' + 1; } if (m == 1) { out.println("YES\n1 2"); continue; } int indI = -1, indJ = -1; for (int i=0; i<n; i++) { for (int j = 0; j < n; j++) { if (i != j && a[i][j] == a[j][i]) { indI = i; indJ = j; } } } if (indI != -1) { out.println("YES"); m++; while (m > 0) { if (m % 2 == 0) out.print((indI + 1) + " "); else out.print((indJ + 1) + " "); m--; } out.println(); continue; } if (m % 2 == 1) { indI = indJ = -1; for (int i=0; i<n && indI == -1; i++) { for (int j = 0; j < n && indJ == -1; j++) { if (i != j && a[i][j] != a[j][i]) { indI = i; indJ = j; } } } if (indI == -1) { out.println("NO"); continue; } out.println("YES"); m++; while (m > 0) { if (m - 2 >= 0) out.print((indI + 1) + " " + (indJ + 1) +" "); else out.print((indI + 1) + " "); m -= 2; } out.println(); continue; } else { indI = -1; indJ = -1; int indK = -1; for (int i = 0; i<n && indI == -1; i++) { for (int j = 0; j<n && indI == -1; j++) { for (int k = 0; k<n && indI == -1; k++) { if (i!=j && i!=k && j!=k && a[i][j] != a[j][i] && a[j][i] == a[i][k] && a[i][j] == a[k][i]) { indI = i; indJ = j; indK = k; } } } } if (indI == -1) { out.println("NO"); continue; } out.println("YES"); if (m % 4 == 0) { m = m / 4; while (m > 0) { out.print((indI + 1) + " " + (indJ + 1) + " " + (indI + 1) + " " + (indK + 1) + " "); m--; } out.print((indI + 1)); out.println(); continue; } else if (m % 4 == 2){ m = m / 4; while (m > 0) { out.print((indJ + 1) + " " + (indI + 1) + " " + (indK + 1) + " " + (indI + 1) + " "); m--; } out.print((indJ + 1) + " " + (indI + 1) + " " + (indK + 1)); out.println(); continue; } } out.println("NO"); } } String input = ""; String output = ""; FastScanner in; PrintWriter out; void run() throws Exception { if (input.length() == 0) { in = new FastScanner(System.in); } else { in = new FastScanner(new File(input)); } if (output.length() == 0) { out = new PrintWriter(System.out); } else { out = new PrintWriter(new File(output)); } solve(); out.close(); } public static void main(String[] args) throws Exception { new D().run(); } class FastScanner { BufferedReader bf; StringTokenizer st; public FastScanner(InputStream is) { bf = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File fr) throws FileNotFoundException { bf = new BufferedReader(new FileReader(fr)); } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.readLine()); } } catch (IOException ex) { ex.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 int[] readIntArray(int length) { int arr[] = new int[length]; for (int i = 0; i<length; i++) arr[i] = nextInt(); return arr; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
61777d7c5aaecb86901bf49971542d0a
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class Main { private static final FastIO fastIO = new FastIO(); private static final String yes = "YES"; private static final String no = "NO"; // a = 0 // b = 1 private static int[][] vers = new int[1001][1001]; private static int[][] connect = new int[1001][2]; public static void main(String[] args) { int t = fastIO.nextInt(); while(t-- > 0){ int n = fastIO.nextInt(); int m = fastIO.nextInt(); for(int i = 0; i < n; i++){ char[] arr = fastIO.nextLine().toCharArray(); for(int j = 0; j < n; j++){ if(arr[j] == '*') continue; vers[i][j] = (arr[j] == 'a')? 0 : 1; } } compute(n, m); } fastIO.printAll(); } public static void compute(int n, int m){ int[] ans = null; for(int i = 0; i < 1001; i++) Arrays.fill(connect[i], -1); cycle : for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i == j) continue; if(vers[i][j] == vers[j][i]) { ans = new int[]{i, j}; break cycle; } connect[i][vers[i][j]] = j; connect[j][vers[j][i]] = i; } } cycle : for(int i = 0; i < n && ans == null; i++){ if(m % 2 == 1){ ans = new int[]{0, 1}; break; } for(int j = 0; j < n; j++){ int v = connect[j][vers[i][j]]; if(i == j) continue; if(v != -1 && vers[v][j] == vers[j][i]) { ans = new int[]{i, j, v}; break cycle; } } } if(ans != null){ fastIO.appendln(yes); if(ans.length == 2) out2(ans, m); else out3(ans, m); fastIO.appendln(); } else fastIO.appendln(no); } public static void out3(int[] ans, int m){ int start = (m % 4 == 0)? 1 : 0; boolean isUp = true; for(int i = start, index = start; i <= m + start; i++){ fastIO.append(ans[index] + 1, " "); index += isUp? 1 : -1; if(index == 0) isUp = true; else if(index == 2) isUp = false; } } public static void out2(int[] ans, int m){ for(int i = 0; i <= m; i++) fastIO.append(ans[i % 2] + 1, " "); } public static class Node { } private static class FastIO { private final BufferedReader in; private final StringBuilder out; private final char LINE_BREAK = '\n'; private StringTokenizer tokens; public FastIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new StringBuilder(); } public String next() { while (tokens == null || !tokens.hasMoreElements()) { try { tokens = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokens.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 str = ""; try { str = in.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public FastIO append(Object... objects){ for(Object o: objects) out.append(o); return this; } public FastIO appendln(Object... objects){ return append(objects).append(LINE_BREAK); } public void printAll(){ System.out.println(out.toString()); } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
7429adc637c32ba803ed0b0619ac8e0b
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]); int i,j; char g[][]=new char[n][n]; for(i=0;i<n;i++) { String st=bu.readLine(); for(j=0;j<n;j++) g[i][j]=st.charAt(j); } if(m%2==1) { sb.append("YES\n"); for(i=0;i<=m;i++) if(i%2==0) sb.append("1 "); else sb.append("2 "); sb.append("\n"); continue; } int x=-1,y=-1; for(i=0;i<n;i++) for(j=0;j<n && x==-1;j++) if(i!=j && g[i][j]==g[j][i]) { x=i+1; y=j+1; break; } if(x!=-1) { sb.append("YES\n"); for(i=0;i<=m;i++) if(i%2==0) sb.append(x+" "); else sb.append(y+" "); sb.append("\n"); continue; } int ans[]=new int[3]; for(i=0;i<n;i++) { ArrayList<Integer> a=new ArrayList<>(),b=new ArrayList<>(); for(j=0;j<n;j++) if(j!=i) { if(g[i][j]=='a') a.add(j); else b.add(j); } if(a.size()>0 && b.size()>0) { ans[0]=i+1; ans[1]=a.get(0)+1; ans[2]=b.get(0)+1; break; } } if(ans[0]!=0) { if(m%4==0) { sb.append("YES\n"); int ti=m/2; for(i=0;i<ti;i++) if(i%2==0) sb.append(ans[0]+" "); else sb.append(ans[1]+" "); sb.append(ans[0]+" "); for(i=0;i<ti;i++) if(i%2==0) sb.append(ans[2]+" "); else sb.append(ans[0]+" "); sb.append("\n"); } else { int ti=m/2; sb.append("YES\n"); for(i=0;i<ti;i++) if(i%2==0) sb.append(ans[1]+" "); else sb.append(ans[0]+" "); sb.append(ans[0]+" "); for(i=0;i<ti;i++) if(i%2==0) sb.append(ans[2]+" "); else sb.append(ans[0]+" "); sb.append("\n"); } } else sb.append("NO\n"); } System.out.print(sb); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
bfb6c536fb938e190e58f78f3f1deee4
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; public class ABGraph { MyScanner scanner = new MyScanner(); String yes = "YES", no = "NO"; private boolean find(String[] labels, int len, LinkedList<Integer> path) { if (len == 0) { return true; } int head = path.get(0), tail = path.get(path.size() - 1); for (int i = 0; i < labels.length; i++) { for (int j = 0; j < labels.length; j++) { if (labels[head].charAt(i) != '*' && labels[i].charAt(head) == labels[tail].charAt(j)) { // Direction is important path.add(0, i); path.add(j); if (find(labels, len - 2, path)) { return true; } path.removeLast(); path.removeFirst(); } } } return false; } private void findPalindrome(String[] labels, int palindromeLen) { LinkedList<Integer> path = new LinkedList<>(); boolean found = false; if (palindromeLen % 2 == 0) { for (int i = 0; i < labels.length && !found; i++) { for (int j = 0; j < labels.length && !found; j++) { if (i != j) { path.addFirst(i); path.addLast(j); if (find(labels, palindromeLen - 2, path)) { found = true; break; } path.removeFirst(); path.removeLast(); } } } } else { for (int i = 0; i < labels.length; i++) { path.add(i); if(find(labels, palindromeLen - 1, path)) { found = true; break; } path.remove(0); } } if (found) { StringBuilder sb = new StringBuilder(); for (int num : path) { sb.append((num + 1) + " "); } System.out.println(yes); System.out.println(sb.toString().substring(0, sb.length() - 1)); } else { System.out.println(no); } } public static void main(String[] args) { ABGraph test = new ABGraph(); int t = test.scanner.nextInt(); for (int i = 0; i < t; i++) { int vertices = test.scanner.nextInt(), palindromeLen = test.scanner.nextInt(); String[] labels = new String[vertices]; for (int j = 0; j < vertices; j++) { labels[j] = test.scanner.nextLine(); } test.findPalindrome(labels, palindromeLen + 1); } } 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
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
88c1a6df578e55640d4b68855b5fda81
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; public void solve() throws IOException { //int t = readInt(); int t = readInt(); for(int f =0;f<t;f++) { int n= readInt(); int m = readInt(); String s[]=new String[n]; for(int i =0;i<n;i++) s[i]= readString(); boolean check = false;; int x=-1; int y=-1; for(int i=0;i<n;i++) { for(int j =i+1;j<n;j++) { if(s[i].charAt(j)==s[j].charAt(i)) { check= true; x=i; y=j; break; } } } if(check) { out.println("YES"); out.print((x+1)+" "); for(int i =0;i<m;i++) { if(i%2==0) { out.print((y+1)+" "); } else out.print((x+1)+" "); } out.println(); } else { if(m%2==1) { out.println("YES"); for(int i =0;i<m+1;i++) { if(i%2==0) out.print(1+" "); else out.print(2+" "); } out.println(); } else { if(n==2) { out.println("NO"); } else { out.println("YES"); x=-1; y=-1; int z=-1; if(s[0].charAt(1)==s[1].charAt(2)) { x=1; y=2; z=3; } else if(s[1].charAt(2)==s[2].charAt(0)) { x=2; y=3; z=1; } else { x=3; y=1; z=2; } int c= m/2-1; int ans[]=new int[3*m+10]; ans[m]=0; ans[m+1]=1; ans[m+2]=2; int left=m; int right=m+2; for(int i= m-1;i>=m-c;i--) { left--; ans[i]= (ans[i+1]%3+2)%3; } for(int i=m+3;i<=m+2+c;i++) { right++; ans[i]= (ans[i-1]+1)%3; } for(int i=left;i<=right;i++) { if(ans[i]==0) out.print(x+" "); else if(ans[i]==1) out.print(y+" "); else out.print(z+" "); } out.println(); } } } } } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v; edge(int u, int v) { this.u=u; this.v=v; } public int compareTo(edge e) { return this.v-e.v; } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
dc2691d982c1358c39c9b9a3c0d5a73d
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); int m=input.nextInt(); char ch[][]=new char[n][n]; for(int i=0;i<n;i++) { String s=input.next(); ch[i]=s.toCharArray(); } int x1=0,y1=0; int f=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(ch[i][j]==ch[j][i]) { x1=(i+1); y1=(j+1); f=1; break; } } } if(f==1) { out.println("YES"); for(int i=0;i<=m;i++) { if(i%2==0) out.print(x1+" "); else out.print(y1+" "); } out.println(); } else { if(n==2) { if(ch[0][1]==ch[1][0]) { out.println("YES"); for(int i=0;i<=m;i++) { if(i%2==0) { out.print(1+" "); } else { out.print(2+" "); } } out.println(); } else { if(m%2!=0) { out.println("YES"); for(int i=0;i<=m;i++) { if(i%2==0) { out.print(1+" "); } else { out.print(2+" "); } } out.println(); } else { out.println("NO"); } } } else { out.println("YES"); boolean c1 = (ch[0][1] == 'a' && ch[1][2] == 'a'); boolean c2 = (ch[0][1] == 'b' && ch[1][2] == 'b'); boolean c3 = (ch[1][2] == 'a' && ch[2][0] == 'a'); boolean c4 = (ch[1][2] == 'b' && ch[2][0] == 'b'); boolean c5 = (ch[2][0] == 'a' && ch[0][1] == 'a'); boolean c6 = (ch[2][0] == 'b' && ch[0][1] == 'b'); int x = 0, y = 0, z = 0; if (c1 || c2) { x = 1;y = 2;z = 3; } else if (c3 || c4) { x = 2;y = 3;z = 1; } else if (c5 || c6) { x = 3;y = 1;z = 2; } if (m % 4 == 1 || m % 4 == 3) { for(int i=0;i<=m;i++) { if(i%2==0) out.print(x+" "); else out.print(y+" "); } out.println(); } else if (m % 4 == 2) { int q=m/4; out.print(x+" "+y+" "+z+" "); for(int i=0;i<q;i++) { out.print(y+" "+x+" "+y+" "+z+" "); } out.println(); } else { int q=m/4; q--; out.print(y+" "+z+" "+y+" "+x+" "+y+" "); for(int i=0;i<q;i++) { out.print(z+" "+y+" "+x+" "+y+" "); } out.println(); } } } } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
ed255e92dd7a414b1c580780b5177baf
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.Scanner; public class D1481 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(), m = sc.nextInt(); String[] mat = new String[n]; for (int i = 0; i < n; i++) { mat[i] = sc.next(); } boolean flag = false; StringBuilder ans = new StringBuilder(); for (int i = 0; i < n && flag == false; i++) { for (int j = i + 1; j < n && flag == false; j++) { char a = mat[i].charAt(j); char b = mat[j].charAt(i); if (a == b || (m & 1) == 1) { flag = true; for (int k = 0; k < m + 1; k++) { if ((k & 1) == 0) { ans.append(i + 1); } else { ans.append(j + 1); } ans.append(" "); } } } } if ((m & 1) == 0 && flag == false && n > 2) { flag = true; for (int i = 0; i < 3; i++) { int zero = i % 3, one = (i + 1) % 3, two = (i + 2) % 3; char a = mat[zero].charAt(one); char b = mat[one].charAt(two); if (a == b) { if ((m / 2 & 1) == 0) { for (int j = 0; j < m / 2 + 1; j++) { if ((j & 1) == 0) ans.append(one + 1); else ans.append(two + 1); ans.append(" "); } for (int j = 0; j < m / 2; j++) { if ((j & 1) == 0) ans.append(zero + 1); else ans.append(one + 1); ans.append(" "); } } else { for (int j = 0; j < m / 2 + 1; j++) { if ((j & 1) == 0) ans.append(zero + 1); else ans.append(one + 1); ans.append(" "); } for (int j = 0; j < m / 2; j++) { if ((j & 1) == 0) ans.append(two + 1); else ans.append(one + 1); ans.append(" "); } } break; } } } if (flag == true) { System.out.println("YES"); System.out.println(ans); } else { System.out.println("NO"); } } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
0e8f6001999316f7e7b1c97ef36550ea
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class AB_Graph { 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 shuffle(int[] a) { Random r = new Random(); for (int i = 0; i <= a.length - 2; i++) { int j = i + r.nextInt(a.length - i); swap(a, i, j); } Arrays.sort(a); } public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } 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(); int m = t.nextInt(); char ch[][] = new char[n][n]; boolean flag = false; for (int i = 0; i < n; ++i) { String s = t.next(); for (int j = 0; j < n; ++j) ch[i][j] = s.charAt(j); } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i != j && ch[i][j] == ch[j][i]) { o.println("YES"); int k = 0; while (k <= m) { if ((k & 1) == 0) o.print(i + 1 + " "); else o.print(j + 1 + " "); ++k; } flag = true; break; } } if (flag) break; } if (!flag) { if ((m & 1) == 1) { o.println("YES"); int k = 0; while (k <= m) { if ((k & 1) == 0) o.print("1 "); else o.print("2 "); ++k; } } else if (n == 2) { o.print("NO"); } else { o.println("YES"); int x = 0, y = 0, z = 0; if (ch[0][1] == ch[1][2]) { x = 1; y = 2; z = 3; } else if (ch[1][2] == ch[2][0]) { x = 2; y = 3; z = 1; } else { x = 3; y = 1; z = 2; } m >>= 1; if ((m & 1) == 1) { for (int i = 0; i < m; ++i) { if ((i & 1) == 0) o.print(x + " "); else o.print(y + " "); } o.print(y + " "); for (int i = 0; i < m; ++i) { if ((i & 1) == 1) o.print(y + " "); else o.print(z + " "); } } else { for (int i = 0; i < m; ++i) { if ((i & 1) == 0) o.print(y + " "); else o.print(x + " "); } o.print(y + " "); for (int i = 0; i < m; ++i) { if ((i & 1) == 1) o.print(y + " "); else o.print(z + " "); } } } } o.println(); } o.flush(); o.close(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
4c5824b8bed66d8238df9b73c3044947
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.text.*; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { input_output(); //out = new PrintWriter(System.out); //in = new Reader(new FileInputStream("card.in")); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static int INF = (int)1e9+2; static int maxn = (int)1e6+5; static int mod = (int)1e9+7; static int n, m, q, t, k; static double pi = 3.141592653589; void solve() throws IOException{ t = in.nextInt(); while (t --> 0) { n = in.nextInt(); m = in.nextInt(); char[][] adj = new char[n][n]; for (int i = 0; i < n; i++) { adj[i] = in.next().toCharArray(); } boolean all = false; int allx = 1, ally = 2; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (adj[i][j] == adj[j][i]) { all = true; allx = i+1; ally = j+1; } } } if (all || m%2 == 1) { out.println("YES"); for (int i = 0; i < m; i++) { if (i%2 == 0) out.print(allx+" "); else out.print(ally+" "); } if (m%2 == 0) out.println(allx); else out.println(ally); continue; } int aax = 0, aay = 0, aaz = 0; int[] have = new int[n+1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { if (adj[i][j] == 'a') have[i+1] = j+1; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; if (adj[i][j] == 'a' && have[j+1] != 0) { aax = i+1; aay = j+1; aaz = have[j+1]; } } } if (aax == 0) out.println("NO"); else { out.println("YES"); if (m != 2) { if ((m/2)%2 == 1) { int tmp = aax; aax = aay; aay = tmp; } out.print(aay); for (int i = 1; i <= m/2; i++) { if (i%2 == 1) out.print(" "+aax); else out.print(" "+aay); } if ((m/2)%2 == 1) { int tmp = aax; aax = aay; aay = tmp; } for (int i = 1; i <= m/2; i++) { if (i%2 == 1) out.print(" "+aaz); else out.print(" "+aay); } out.println(); } else { out.println(aax+" "+aay+" "+aaz); } } } } //<> static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if(f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if(f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
4b09d047abc6502aea1f4d6a2961bbf7
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class d { public static void main(String[] args) { FastScanner scan=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int t=scan.nextInt(); t:for(int tt=0;tt<t;tt++) { int n=scan.nextInt(), k=scan.nextInt(); char[][] a=new char[n][n]; for(int i=0;i<n;i++) a[i]=scan.next().toCharArray(); int[] ina=new int[n], outa=new int[n], inb=new int[n], outb=new int[n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) continue; if(a[i][j]=='a') { ina[j]++; outa[i]++; } else { inb[j]++; outb[i]++; } } } if(k%2==1) { out.println("YES"); for(int i=0;i<=k;i++) { out.print(((i%2)+1)+" "); } out.println(); } else { for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(a[i][j]==a[j][i]) { out.println("YES"); for(int x=0;x<=k;x++) { if(x%2==0) out.print((i+1)); else out.print((j+1)); out.print(" "); } out.println(); continue t; } } } for(int i=0;i<n;i++) { if((ina[i]>0&&outa[i]>0)||(inb[i]>0&&outb[i]>0)) { char letter; if(ina[i]>0&&outa[i]>0) letter='a'; else letter='b'; //verify this out.println("YES"); int outToLetter=-1, inFromLetter=-1; for(int j=0;j<n;j++) { if(a[i][j]==letter) outToLetter=j; else if(a[j][i]==letter) inFromLetter=j; } if((k/2)%2==0) { out.print((i+1)+" "); for(int x=0;x<k/2;x++) { if(x%2==0) out.print((inFromLetter+1)); else out.print((i+1)); out.print(" "); } for(int x=0;x<k/2;x++) { if(x%2==0) out.print((outToLetter+1)); else out.print((i+1)); out.print(" "); } } else { // System.out.println(i+" "+inFromLetter+" "+outToLetter); out.print((inFromLetter+1)+" "); for(int x=0;x<k;x++) { if(x%4==0) out.print((i+1)); else if(x%4==1) out.print((outToLetter+1)); else if(x%4==2) out.print((i+1)); else out.print((inFromLetter+1)); out.print(" "); } } out.println(); continue t; } } out.println("NO"); } } out.close(); } /* 1 3 2 *ba a*a bb* */ 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
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
0f1c425af9da61dd1d9772a950237f9a
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int tc = sc.nextInt(); cases: while (tc-- > 0) { int n = sc.nextInt(), m = sc.nextInt(); boolean[][] adj = new boolean[n][n]; for (int i = 0; i < n; i++) { char[] s = sc.next().toCharArray(); for (int j = 0; j < n; j++) adj[i][j] = i != j && s[j] == 'a'; } int both = -1; for (int i = 0; i < n; i++) for (int j = 0; j < i; j++) { if (adj[i][j] == adj[j][i] || m % 2 == 1) { out.println("YES"); for (int k = 0; k <= m; k++) out.printf("%d ", k % 2 == 0 ? i + 1 : j + 1); out.println(); continue cases; } } for (int i = 0; i < n; i++) { boolean foundA = false, foundB = false; for (int j = 0; j < n; j++) { if (i == j) continue; if (adj[i][j]) foundA = true; else foundB = true; } if (foundA && foundB) both = i; } if (both != -1) { out.println("YES"); int a = -1, b = -1; for (int j = 0; j < n; j++) if (both != j) { if (adj[both][j]) a = j; else b = j; } if(m%4==0) { out.print(both+1); for (int k = 0; k < m / 2; k++) out.printf(" %d", k % 2 == 0 ? a + 1 : both + 1); for (int k = 0; k < m / 2; k++) out.printf(" %d", k % 2 == 0 ? b + 1 : both + 1); } else { out.print(a+1); for (int k = 0; k < m / 2; k++) out.printf(" %d", k % 2 == 0 ? both + 1 : a + 1); for (int k = 0; k < m / 2; k++) out.printf(" %d", k % 2 == 0 ? b + 1 : both + 1); } out.println(); continue cases; } out.println("NO"); } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready() || st.hasMoreTokens(); } int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
a65b038efa564959dbf1e7435c27b971
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class EdE { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] omkar) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int t = sc.nextInt(); for(int i = 0;i<t;i++){ // String input1 = bf.readLine().trim(); // String input2 = bf.readLine().trim(); // COMPARING INTEGER OBJECTS U DO DOT EQUALS NOT == int n = sc.nextInt(); int m = sc.nextInt(); char[][] grid = new char[n+1][n+1]; for(int j = 0;j<n;j++){ String s = sc.next(); for(int k =0 ;k<n;k++){ grid[j+1][k+1] = s.charAt(k); } } boolean found = false; int index1 = -1; int index2 = -1; for(int j = 1;j<=n;j++){ for(int k = j+1;k<=n;k++){ if (grid[j][k] == grid[k][j]){ found = true; index1 = j; index2 = k; break; } } if (found) break; } if (found){ out.println("YES"); for(int j = 0;j<=m;j++){ if (j%2 ==0) out.print(index1 + " "); else out.print(index2 + " "); } out.println(); } else if (n == 2 && m%2 == 0){ out.println("NO"); } else if (n == 2){ out.println("YES"); for(int j = 0;j<=m;j++){ if (j%2 ==0) out.print(1 + " "); else out.print(2 + " "); } out.println(); } else if (m%2 == 1){ out.println("YES"); for(int j = 0;j<=m;j++){ if (j%2 ==0) out.print(1 + " "); else out.print(2 + " "); } out.println(); } else{ out.println("YES"); ArrayList<Integer> outa = new ArrayList<Integer>(); ArrayList<Integer> outb = new ArrayList<Integer>(); for(int j = 2;j<=n;j++){ if (grid[1][j] == 'a') outa.add(j); else outb.add(j); } if (!outa.isEmpty() && !outb.isEmpty()){ int ver = 1; int index3 = outa.get(0); int index4 = outb.get(0); run( ver, index3, index4, m); } else if (outa.isEmpty()){ int v1 = outb.get(0); int v2 = outb.get(1); if (grid[v1][v2] == 'b'){ int index3 = 1; int index4 = v2; int ver = v1; run( ver, index3, index4, m); } else{ int index3 = 1; int index4 = v1; int ver = v2; run( ver, index3, index4, m); } } else{ int v1 = outa.get(0); int v2 = outa.get(1); if (grid[v1][v2] == 'a'){ int index3 = v2; //ver--> index3 is 'a', ver--> index4 is 'b' int index4 = 1; int ver = v1; run( ver, index3, index4, m); } else{ int index3 = v1; int index4 = 1; int ver = v2; run( ver, index3, index4, m); } } } } out.close(); } public static void run(int ver, int index3, int index4, int m){ if (m%4 == 0){ for(int j = 0;j<=m;j++){ if (j%4 == 0 || j%4 == 2){ out.print(ver + " "); } else if (j%4 == 1){ out.print(index3 + " "); } else{ out.print(index4 + " "); } } } else{ for(int j = 0;j<=m;j++){ if (j%4 == 1 || j%4 == 3){ out.print(ver + " "); } else if (j%4 == 0){ out.print(index3 + " "); } else{ out.print(index4 + " "); } } } out.println(); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
73bc1bd622292b2b098f1dba4aec9e18
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
//stan hu tao import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class x1481D { public static void main(String hi[]) throws Exception { int[] map = new int[420]; map['a'] = 0; map['b'] = 1; FastScanner infile = new FastScanner(); int T = infile.nextInt(); StringBuilder sb = new StringBuilder(); matcha:while(T-->0) { int N = infile.nextInt(); int K = infile.nextInt(); char[][] grid = new char[N][N]; for(int r=0; r < N; r++) grid[r] = infile.nextLine().toCharArray(); if(K%2 == 1) { sb.append("YES\n"); sb.append("1 "); for(int i=0; i < K; i++) { if((i%2) == 0) sb.append("2 "); else sb.append("1 "); } sb.append("\n"); } else if(K > 1) { for(int a=0; a < N; a++) for(int b=a+1; b < N; b++) if(grid[a][b] == grid[b][a]) { sb.append("YES\n"); int curr = a+1; sb.append(curr+" "); for(int i=0; i < K; i++) { if(curr == a+1) curr = b+1; else curr = a+1; sb.append(curr+" "); } sb.append("\n"); continue matcha; } if(N == 2) sb.append("NO\n"); else { sb.append("YeS\n"); //1 2 3 int x = map[grid[0][1]]; int y = map[grid[1][2]]; int z = map[grid[2][0]]; if(x+y+z == 0 || x+y+z == 3) { sb.append("1 "); int curr = 2; for(int i=0; i < K; i++) { sb.append(curr+" "); curr++; if(curr == 4) curr = 1; } sb.append("\n"); continue matcha; } else if(x+y+z == 1) { x ^= 1; y ^= 1; z ^= 1; } int[] arr = new int[3]; arr[0] = x; arr[1] = y; arr[2] = z; int[] tags = new int[3]; tags[0] = 1; tags[1] = 2; tags[2] = 3; if(K%3 == 0) { //bab while(arr[0] != 1 || arr[2] != 1) { arr = cyc(arr); tags = cyc(tags); } } else if(K%3 == 1) { //abb while(arr[1] != 1 || arr[2] != 1) { arr = cyc(arr); tags = cyc(tags); } } else { //bba while(arr[0] != 1 || arr[1] != 1) { if(debug){ print(arr); print(tags); } arr = cyc(arr); tags = cyc(tags); if(debug){ print(arr); print(tags); } } } //print int curr = tags[0]; sb.append(curr+" "); for(int i=0; i < K; i++) { curr++; if(curr >= 4) curr = 1; sb.append(curr+" "); } sb.append("\n"); } } else { sb.append("yES\n"); sb.append("1 2\n"); } } System.out.print(sb); } public static int[] cyc(int[] arr) { int[] brr = new int[3]; for(int i=0; i < 3; i++) brr[i] = arr[(i+1)%3]; return brr; } static boolean debug = false; public static void print(int[] arr) { //for debugging only for(int x: arr) System.out.print(x+" "); System.out.println(); } } /* 1 3 8 *ba a*a bb* */ class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
e01e74d17e51ae0b5f28033d4887a66f
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class D { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(f.readLine()); while(t-->0){ StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[][] mat = new char[n][n]; for(int i = 0; i < n; i++) mat[i] = f.readLine().toCharArray(); if(m % 2 == 1){ out.println("YES"); StringBuilder ans = new StringBuilder(); for(int i = 0; i < m+1; i++){ if(i % 2 == 0) ans.append("1 "); else ans.append("2 "); } out.println(ans.toString().trim()); }else { boolean found = false; int idx1 = -1; int idx2 = -1; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (mat[i][j] == mat[j][i]) { found = true; idx1 = i+1; idx2 = j+1; break; } } if (found) break; } if (found){ out.println("YES"); StringBuilder ans = new StringBuilder(); for (int i = 0; i < m + 1; i++) { if (i % 2 == 0) ans.append(idx1 + " "); else ans.append(idx2 + " "); } out.println(ans.toString().trim()); }else{ if(n == 2){ out.println("NO"); continue; } int n1 = -1; int n2 = -1; int n3 = -1; boolean[] as = new boolean[n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(mat[i][j] == 'a'){ as[i] = true; break; } } } boolean fnd = false; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(mat[i][j] == 'a' && as[j]){ for(int k = 0; k < n; k++){ if(mat[j][k] == 'a'){ n1=i; n2=j; n3=k; fnd = true; break; } } } if(fnd) break; } if(fnd) break; } int nlen = (m-2)/2; StringBuilder ans = new StringBuilder(); if(nlen % 2 == 0){ for(int i = 0; i < nlen; i++){ if(i % 2 == 0) ans.append((n1+1)+" "); else ans.append((n2+1)+" "); } }else{ for(int i = 0; i < nlen; i++){ if(i % 2 == 0) ans.append((n2+1)+" "); else ans.append((n1+1)+" "); } } ans.append((n1+1)+" "); ans.append((n2+1)+" "); ans.append((n3+1)+" "); for(int i = nlen+3; i < m+1; i++){ if(i % 2 == (nlen+3) % 2) ans.append((n2+1)+" "); else ans.append((n3+1)+" "); } out.println("YES"); out.println(ans.toString().trim()); } } } out.close(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
d98192627f605f791ca33cb3b338b1fd
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ public class D { private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; public static void process() throws IOException { int n = sc.nextInt(),m = sc.nextInt(); int arr[][] = new int[n+1][n+1]; for(int i=0; i<n;i++) { String str = sc.next(); for(int j=0; j<n; j++) { if(i == j)continue; arr[i][j] = str.charAt(j) - 'a'+1; } } if(m%2 == 1) { System.out.println("YES"); for(int i=0; i<=m; i++) { if(i%2 == 1)System.out.print(1+" "); else System.out.print(2+" "); } System.out.println(); return; } for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(i == j)continue; if(arr[i][j] == arr[j][i]) { System.out.println("YES"); for(int ii=0; ii<=m; ii++) { if(ii%2 == 1)System.out.print((i+1)+" "); else System.out.print((j+1)+" "); } System.out.println(); return; } } } for(int i=0; i<n; i++) { int a = 0,b = 0; for(int j=0; j<n; j++) { if(arr[i][j] == 1)a = j+1; if(arr[i][j] == 2)b = j+1; } if(a > 0 && b > 0) { System.out.println("YES"); if(m%4==0) { for(int j=0;j<=m;j++) { if(j%2==0) System.out.print((i+1)+" "); else { if(j<m/2) System.out.print(a+" "); else System.out.print(b+" "); } } } else { for(int j=0;j<=m;j++) { if(j%2==1) System.out.print((i+1)+" "); else { if(j<m/2) System.out.print(a+" "); else System.out.print(b+" "); } } } return; } } System.out.println("NO"); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= static FastScanner sc; static PrintWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new PrintWriter(System.out); } else { sc = new FastScanner(100); out = new PrintWriter("output.txt"); } int t = 1; t = sc.nextInt(); while (t-- > 0) { process(); } out.flush(); out.close(); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Pair)) return false; // Pair key = (Pair) o; // return x == key.x && y == key.y; // } // // @Override // public int hashCode() { // int result = x; // result = 31 * result + y; // return result; // } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static void println(Object o) { out.println(o); } static void println() { out.println(); } static void print(Object o) { out.print(o); } static void pflush(Object o) { out.println(o); out.flush(); } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int abs(int x) { return Math.abs(x); } static long abs(long x) { return Math.abs(x); } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } public static long lca(long a, long b) { return (a * b) / gcd(a, b); } public static int lca(int a, int b) { return (a * b) / gcd(a, b); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(int a) throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) throws IOException { int[] A = new int[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextInt(); } return A; } long[] readArrayLong(int n) throws IOException { long[] A = new long[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextLong(); } return A; } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
9abf0e8b54342b990318e7b35d0ada8f
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
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 TheTreasureOfTheSegments { 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; int res = 0; public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException { while(testNumber-->0){ int n = in.nextInt(); int m = in.nextInt(); char g[][] = new char[n][]; for (int i = 0; i < n; i++) { g[i] = in.next().toCharArray(); } if (n == 2) { if (m % 2 == 0 && g[0][1] != g[1][0]) out.println("NO"); else { out.println("YES"); for (int k = 0; k <= m; k++) { out.print((2 - k % 2) + " "); } out.println(); } continue; } boolean found = false; X: for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (g[i][j] == g[j][i]) { out.println("YES"); for (int k = 0; k <= m; k++) { if (k % 2 == 0) out.print((i + 1) + " "); else out.print((j + 1) + " "); } out.println(); // return; found = true; break X; } } } if(found) continue; int v1 = -1, v2 = -1, v3 = -1; for (int i = 0; i < n; i++) { v2 = -1; v3 = -1; for (int j = 0; j < n; j++) { if (g[i][j] == 'a') v2 = j; else if (g[i][j] == 'b') v3 = j; } if (v2 != -1 && v3 != -1) { v1 = i; break; } } out.println("YES"); if (m % 4 == 0) { for (int k = 0; k < m / 4; k++) { out.print((v1 + 1) + " " + (v2 + 1) + " " + (v1 + 1) + " " + (v3 + 1) + " "); } out.println(v1 + 1); } else if (m % 4 == 2) { out.print((v2 + 1) + " "); for (int k = 0; k < m / 4; k++) { out.print((v1 + 1) + " " + (v2 + 1) + " " + (v1 + 1) + " " + (v3 + 1) + " "); } out.println((v1 + 1) + " " + (v3 + 1)); } else { for (int k = 0; k <= m / 2; k++) { out.print((v1 + 1) + " " + (v2 + 1) + " "); } out.println(); } } } 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(boolean 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); } 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
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
5145cb3ab1f7116099474733c263d003
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class Main { static FastScanner sc = new FastScanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); static ArrayList<TreeSet<Integer>> mapA,mapB; public static void main(String[] args) throws Exception { int Q = sc.nextInt(); for(int i = 0; i < Q; i++) solve(); pw.flush(); } static void solve(){ int N = sc.nextInt(); int M = sc.nextInt(); char[][] map = new char[N][]; for(int i = 0; i < N; i++){ map[i] = sc.next().toCharArray(); } if(M % 2 == 0){ boolean flg = false; for(int i = 0; i < N; i++){ for(int j = i+1; j < N; j++){ if(map[i][j] == map[j][i]){ sb.append(j+1).append(" "); for(int k = 0; k < M/2; k++){ sb.append(i+1).append(" ").append(j+1).append(" "); flg = true; } break; } } if(flg) break; } if(!flg){ ArrayDeque<Integer> dq = new ArrayDeque<Integer>(); int left = 0; int right = 0; for(int i = 0; i < N; i++){ int isA = -1; int isB = -1; for(int j = 0; j < N; j++){ if(i == j) continue; if(map[i][j] == 'a'){ isA = i; }else{ isB = i; } } if(isA != -1 && isB != -1){ left = right = i; dq.addFirst(i+1); flg = true; break; } } if(!flg){ pw.println("NO"); }else{ while(M > 0){ flg = false; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ if(i == left || j == right) continue; if(map[left][i] == map[j][right]){ left = i; dq.addFirst(i+1); right = j; dq.addLast(j+1); flg = true; break; } } if(flg) break; } M -= 2; } //pw.println(dq); pw.println("YES"); while(dq.size() > 0) sb.append(dq.poll()).append(" "); pw.println(sb.toString().trim()); } }else{ pw.println("YES"); pw.println(sb.toString().trim()); } }else{ for(int i = 0; i < (M+1)/2; i++){ sb.append(1).append(" ").append(2).append(" "); } pw.println("YES"); pw.println(sb.toString().trim()); } sb.setLength(0); return; } private static String ArraysToString(int[] arr){ String s = Arrays.toString(arr); s = s.replaceAll(",",""); s = s.substring(1,s.length()-1); return s; } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); int randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } public static void save_sort(long[] array) { shuffle(array); Arrays.sort(array); } public static long[] shuffle(long[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); long randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } } } class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String[] nextArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } 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; } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
98e29f42141d14fcb5463377e8873246
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; /** * author:王跃坤 JAVA算法交流群:323348662 */ public class D { public static void main(String[] args) { // Scanner sc=new Scanner(System.in); FastScanner sc=new FastScanner(); FastOutput out=new FastOutput(System.out); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int m=sc.nextInt(); char c[][]=new char[n][n]; for(int i=0;i<n;i++){ c[i]=sc.next().toCharArray(); } boolean over=false; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(c[i][j]==c[j][i]){ out.println("YES"); StringBuilder sb=new StringBuilder(); for(int k=0;k<m;k++){ if(k%2==0){ sb.append((i+1)+" "); }else{ sb.append((j+1)+" "); } } if(m%2==0){ sb.append((i+1)); }else{ sb.append((j+1)); } out.println(sb.toString()); over=true; i=n;j=n; } } } if(!over){ if(m%2==0){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ if(c[i][j]!='*'&&c[i][j]==c[k][i]){ over=true; out.println("YES"); StringBuilder sb=new StringBuilder(); int anss[]=new int[m+1]; anss[m/2]=i+1; for(int cnt=1;cnt<=m/2;cnt++){ if(cnt%2==0){ anss[cnt+m/2]=i+1; anss[m/2-cnt]=i+1; }else{ anss[cnt+m/2]=k+1; anss[m/2-cnt]=j+1; } } for(int cnt=0;cnt<=m;cnt++){ if(cnt==m){ sb.append(anss[cnt]); }else{ sb.append(anss[cnt]+" "); } } out.println(sb.toString()); i=n;j=n;k=n; } } } } if(!over) out.println("NO"); }else{ for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(c[i][j]!=c[j][i]){ out.println("YES"); StringBuilder sb=new StringBuilder(); for(int k=0;k<m;k++){ if(k%2==0){ sb.append((i+1)+" "); }else{ sb.append((j+1)+" "); } } if(m%2==0){ sb.append((i+1)); }else{ sb.append((j+1)); } out.println(sb.toString()); over=true; i=n;j=n; } } } } } } out.close(); } 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[] readIntArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 1 << 13; private final Writer os; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput append(String c) { cache.append(c); afterWrite(); return this; } public FastOutput println(String c) { return append(c).println(); } public FastOutput println() { return append(System.lineSeparator()); } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
fbece5898b5d24ff62f95fe6a24e9f21
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class CFD { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; void solve() { int T = nextInt(); // int T = 1; for (int i = 0; i < T; i++) { helper(); } } int n; char[][] mat; void helper() { n = nextInt(); int m = nextInt(); mat = new char[n][n]; for (int i = 0; i < n; i++) { mat[i] = nextString().toCharArray(); } if (m % 2 == 1) { List<Integer> res = find(m, 1, 2); outln(yes.toUpperCase()); for (int v : res) { out(v + " "); } outln(""); return; } // If there is a loop. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (mat[i][j] == mat[j][i]) { List<Integer> res = find(m, i + 1, j + 1); outln(yes.toUpperCase()); for (int v : res) { out(v + " "); } outln(""); return; } } } Pair pair = findPair('a'); if (pair == null) { pair = findPair('b'); } if (pair == null) { outln(no.toUpperCase()); return; } Deque<Integer> deck = new LinkedList<>(); deck.add(pair.left); deck.add(pair.middle); deck.add(pair.right); m -= 2; int parity = 0; for (int i = 0; i < m / 2; i++) { int left = parity == 0 ? pair.middle : pair.left; int right = parity == 0 ? pair.middle : pair.right; parity = 1 - parity; deck.addFirst(left); deck.addLast(right); } outln(yes.toUpperCase()); for (int v : deck) { out((1 + v) + " "); } outln(""); } Pair findPair(char target) { int[] inDegree = new int[n]; int[] outDegree = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (mat[i][j] == target) { outDegree[i]++; inDegree[j]++; } } } int middle = -1; for (int i = 0; i < n; i++) { if (inDegree[i] > 0 && outDegree[i] > 0) { middle = i; break; } } if (middle == -1) { return null; } int left = -1; int right = -1; for (int i = 0; i < n; i++) { if (mat[i][middle] == target) { left = i; } if (mat[middle][i] == target) { right = i; } } return new Pair(left, middle, right); } class Pair { int left; int middle; int right; public Pair(int left, int middle, int right) { this.left = left; this.middle = middle; this.right = right; } } List<Integer> find(int m, int first, int second) { List<Integer> res = new ArrayList<>(); res.add(first); int start = second; for (int i = 0; i < m; i++) { res.add(start); start = start == first ? second : first; } return res; } void shuffle(long[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); long tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFD() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) { new CFD(); } public long[] nextLongArr(int n) { long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
e627db42ddf252ce074fc391b63adfb1
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 1e9 + 10; static final long OO = (long) 2e18 + 10; static final int MOD = (int) 1e9 + 7; static char[][] g; static void solve() { int n = in.nextInt(); int m = in.nextInt(); g = new char[n][]; for (int i = 0; i < n; i++) { g[i] = in.next().toCharArray(); } if (n == 2) { if (m % 2 == 0 && g[0][1] != g[1][0]) out.println("NO"); else { out.println("YES"); for (int k = 0; k <= m; k++) { out.print((2 - k % 2) + " "); } out.println(); } return; } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (g[i][j] == g[j][i]) { out.println("YES"); for (int k = 0; k <= m; k++) { if (k % 2 == 0) out.print((i + 1) + " "); else out.print((j + 1) + " "); } out.println(); return; } } } int v1 = -1, v2 = -1, v3 = -1; for (int i = 0; i < n; i++) { v2 = -1; v3 = -1; for (int j = 0; j < n; j++) { if (g[i][j] == 'a') v2 = j; else if (g[i][j] == 'b') v3 = j; } if (v2 != -1 && v3 != -1) { v1 = i; break; } } out.println("YES"); if (m % 4 == 0) { for (int k = 0; k < m / 4; k++) { out.print((v1 + 1) + " " + (v2 + 1) + " " + (v1 + 1) + " " + (v3 + 1) + " "); } out.println(v1 + 1); } else if (m % 4 == 2) { out.print((v2 + 1) + " "); for (int k = 0; k < m / 4; k++) { out.print((v1 + 1) + " " + (v2 + 1) + " " + (v1 + 1) + " " + (v3 + 1) + " "); } out.println((v1 + 1) + " " + (v3 + 1)); } else { for (int k = 0; k <= m / 2; k++) { out.print((v1 + 1) + " " + (v2 + 1) + " "); } out.println(); } } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int T = 1; T = in.nextInt(); while (T-- > 0) solve(); out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
0edc5a2d934957c1edeb8d3596041301
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class ABGraph_1481D { public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t -- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[][] grid = new char[n][]; for(int i = 0; i < n; i ++) grid[i] = br.readLine().toCharArray(); StringBuilder output = new StringBuilder(); if(m % 2 == 1) { System.out.println("YES"); int[] arr = new int[] {1, 2}; for(int i = 0; i <= m; i ++) output.append(arr[i % 2] + " "); } else { if(n == 2 && grid[0][1] != grid[1][0]) { System.out.println("NO"); } else { System.out.println("YES"); if(n == 2) { int[] arr = new int[] {1, 2}; for(int i = 0; i <= m; i ++) output.append(arr[i % 2] + " "); } else { char x = grid[0][1], y = grid[1][2], z = grid[2][0]; int[] arr = new int[] {1, 2, 3}; if(x == y && x == z) { for(int i = 0; i <= m; i ++) output.append(arr[i % 3] + " "); } else { int start = x == y? 1 : y == z? 2 : 0; Deque<Integer> dq = new LinkedList<>(); dq.add(arr[start]); int l = start, r = start, ct = m / 2; while(ct > 0) { l = (l + 2) % 3; r = (r + 1) % 3; dq.addFirst(arr[l]); dq.addLast(arr[r]); ct --; } while(!dq.isEmpty()) output.append(dq.pollFirst() + " "); } } } } if(output.length() > 0) System.out.println(output.toString()); } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
b90a21f1aa976be4d91fb8b511ceeb75
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ for(int q=ni();q>0;q--){ work(); out.println(); } out.flush(); } long mod=998244353; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } int[][] graph; void work() { int n=ni(),m=ni(); graph=new int[n][n]; for(int i=0;i<n;i++){ String str=ns(); for(int j=0;j<n;j++){ char c=str.charAt(j); if(i!=j&&c=='a'){ graph[i][j]=1; } } } if(m%2==1){ out.println("YES"); out.print(1+" "); for(int i=1;i<=m;i++){ out.print(((i%2)+1)+" "); } }else{ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i!=j&&graph[i][j]==graph[j][i]){ out.println("YES"); out.print((i+1)+" "); for(int k=1;k<=m;k++){ if(k%2==1){ out.print((j+1)+" "); }else{ out.print((i+1)+" "); } } return; } } } int a=-1,b=-1,c=-1,d=-1; for(int i=0;i<n;i++){ a=-1;b=-1;c=-1;d=-1;; for(int j=0;j<n;j++){ if(i!=j){ if(graph[i][j]==0){ a=j; }else if(graph[j][i]==0){ b=j; }else if(graph[i][j]==1){ c=j; }else if(graph[j][i]==1){ d=j; } } } int n1=-1,n2=-1; if(a!=-1&&b!=-1){ n1=a;n2=b; }else if(c!=-1&&d!=-1){ n1=c;n2=d; } if(n1!=-1){ out.println("YES"); n1++;n2++; int n0=i+1; int s=m/2; if(m%4==0){ out.print(n0+" "); for(int j=0;j<s;j++){ if(j%2==0){ out.print(n1+" "); }else{ out.print(n0+" "); } } for(int j=0;j<s;j++){ if(j%2==0){ out.print(n2+" "); }else{ out.print(n0+" "); } } }else{ out.print(n1+" "); for(int j=0;j<s;j++){ if(j%2==1){ out.print(n1+" "); }else{ out.print(n0+" "); } } for(int j=0;j<s;j++){ if(j%2==0){ out.print(n2+" "); }else{ out.print(n0+" "); } } } return; } } out.print("NO"); } } //input @SuppressWarnings("unused") private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
67cb2e8cffa244f3cf7b21dd9becf59e
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class abgraph { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = scan.nextInt(); for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(), m = scan.nextInt(); char[][] graph = new char[n][n]; int[][] incoming = new int[n][2], outgoing = new int[n][2]; for(int i = 0; i < n; i++) { for(int j = 0; j < 2; j++) { incoming[i][j] = outgoing[i][j] = -1; } } for(int i = 0; i < n; i++) { graph[i] = scan.next().toCharArray(); for(int j = 0; j < n; j++) { if(i == j) continue; incoming[j][graph[i][j] - 'a'] = i; outgoing[i][graph[i][j] - 'a'] = j; } } if(m % 2 == 1) { out.println("YES"); for(int i = 0; i <= m; i++) { out.printf("%d ", i % 2 + 1); } out.println(); return; } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if(graph[i][j] == graph[j][i]) { out.println("YES"); for(int k = 0; k <= m; k++) { out.printf("%d ", k % 2 == 0 ? i + 1 : j + 1); } out.println(); return; } } } for(int i = 0; i < n; i++) { for(int j = 0; j < 2; j++) { if(incoming[i][j] != -1 && outgoing[i][j] != -1) { out.println("YES"); int parity = m / 2 % 2; for(int k = 0; k <= m / 2; k++) { out.printf("%d ", (k + parity) % 2 == 0 ? i + 1 : incoming[i][j] + 1); } for(int k = 0; k < m / 2; k++) { out.printf("%d ", k % 2 == 1 ? i + 1 : outgoing[i][j] + 1); } out.println(); return; } } } out.println("NO"); } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
db50d4c4230f87d6bfc37d78d53fb63c
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.StringTokenizer; public class Solution{ public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = fs.nextInt(); outer: while(tt-->0) { int n = fs.nextInt(); int m = fs.nextInt(); char[][] a = new char[n][n]; boolean[][] to = new boolean[n][2], from = new boolean[n][2]; for(int i=0;i<n;i++) { a[i] = fs.next().toCharArray(); for(int j=0;j<n;j++) { if(i==j) continue; to[j][a[i][j]-'a'] = true; from[i][a[i][j]-'a'] = true; } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) continue; if(a[i][j]==a[j][i]) { out.println("YES"); out.print(i+1+" "+(j+1)+" "); for(int k=0;k<m-1;k++) { if(k%2==0) { out.print(i+1+" "); } else { out.print(j+1+" "); } } out.println(); continue outer; } } } if(m%2!=0) { out.println("YES"); out.print("1 "); for(int i=0;i<m;i++) { if(i%2==0) { out.print("2 "); } else { out.print("1 "); } } out.println(); continue outer; } int y = -1; char ch = 'a'; for(int i=0;i<n;i++) { if(to[i][0]&&from[i][0]) { y = i; ch = 'a'; break; } if(to[i][1] && from[i][1]) { y = i; ch = 'b'; break; } } if(y==-1) { out.println("NO"); continue outer; } int x = -1, z = -1; for(int i=0;i<n;i++) { if(a[i][y]==ch) { x = i; break; } } for(int i=0;i<n;i++) { if(a[y][i]==ch) { z = i; break; } } x++; y++; z++; out.println("YES"); if((m/2)%2!=0) { out.print(x + " " + y + " " + z+" "); m -= 2; m /= 4; for(int i=0;i<m;i++ ) { out.print(y+" "+x+" "+y+" "+z+" "); } out.println(); } else { out.print(y+" "); m /= 4; for(int i=0;i<m;i++) { out.print(z+" "+y+" "+x+" "+y+" "); } out.println(); } } out.close(); } static final Random random=new Random(); static <T> void shuffle(T[] arr) { int n = arr.length; for(int i=0;i<n;i++ ) { int k = random.nextInt(n); T temp = arr[k]; arr[k] = arr[i]; arr[i] = temp; } } static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void reverse(int[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static void reverse(long[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static <T> void reverse(T[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++) { T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
57bb91a31f339dc037f2190850ecf13e
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Practice { public static void main(String[] args) throws NumberFormatException, IOException { Scanner s = new Scanner(System.in); int t = s.nextInt(); while ((t--) > 0) { int n = s.nextInt(); int k = s.nextInt(); char[][] arr = new char[n][n]; for (int i = 0; i < n; i++) { String str = s.next(); for (int j = 0; j < n; j++) { arr[i][j] = str.charAt(j); } } getAns(n, k, arr); } } private static void getAns(int n, int k, char[][] arr) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { continue; } if (arr[i][j] == arr[j][i]) { System.out.println("YES"); StringBuilder str = new StringBuilder(); for (int q = 0; q <= k; q++) { if (q % 2 == 0) { str.append((i + 1) + " "); } else { str.append((j + 1) + " "); } } System.out.println(str); return; } } } if (k % 2 != 0) { System.out.println("YES"); StringBuilder str = new StringBuilder(); for (int q = 0; q <= k; q++) { if (q % 2 == 0) { str.append((1) + " "); } else { str.append((2) + " "); } } System.out.println(str); return; } k = k / 2; int one = -1, two = -1, three = -1; for (int i = 0; i < n; i++) { int a1 = 0, b1 = 0, a2 = 0, b2 = 0; for (int j = 0; j < n; j++) { if (arr[j][i] == 'a') { a1 = 1; } else if(arr[j][i] == 'b'){ b1 = 1; } if (arr[i][j] == 'a') { a2 = 1; } else if(arr[i][j] == 'b'){ b2 = 1; } }//System.out.println(a1+" "+a2+" "+b1+" "+b2); if (a1 == 1 && a2 == 1) { one = -1; two = i + 1; three = -1; for (int j = 0; j < n; j++) { if (arr[j][i] == 'a' && one == -1) { one = j + 1; } if (arr[i][j] == 'a' && three == -1) { three = j + 1; } } break; } else if (b1 == 1 && b2 == 1) { one = -1; two = i + 1; three = -1; for (int j = 0; j < n; j++) { if (arr[j][i] == 'b' && one == -1) { one = j + 1; } if (arr[i][j] == 'b' && three == -1) { three = j + 1; } } break; } }//System.out.println(one+" "+two+" "+three); if (one == -1) { System.out.println("NO"); return; } System.out.println("YES"); StringBuilder str=new StringBuilder(); if (k % 2 == 0) { int c=2,d=1; for (int i = 0; i <= 2*k; i++) { if(c==2&&d==1) { str.append(two+" "); c=3; }else if(c==3) { str.append(three+" "); c=2; d=-1; }else if(c==1) { str.append(one+" "); c=2;d=1; }else{ str.append(two+" "); c=1; } } } else { int c=1,d=1; for (int i = 0; i <= 2*k; i++) { if(c==2&&d==1) { str.append(two+" "); c=3; }else if(c==3) { str.append(three+" "); c=2; d=-1; }else if(c==1) { str.append(one+" "); c=2;d=1; }else{ str.append(two+" "); c=1; } } }System.out.println(str); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
9d9a10bdebd2c06a664c3aa6620ea0bf
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class D { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = scan.nextInt(); for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(), m = scan.nextInt(); char[][] graph = new char[n][n]; int[][] incoming = new int[n][2], outgoing = new int[n][2]; for(int i = 0; i < n; i++) { for(int j = 0; j < 2; j++) { incoming[i][j] = outgoing[i][j] = -1; } } for(int i = 0; i < n; i++) { graph[i] = scan.next().toCharArray(); for(int j = 0; j < n; j++) { if(i == j) continue; incoming[j][graph[i][j] - 'a'] = i; outgoing[i][graph[i][j] - 'a'] = j; } } // Always answer for odd length if(m % 2 == 1) { out.println("YES"); for(int i = 0; i <= m; i++) { out.printf("%d ", i % 2 + 1); } out.println(); return; } //Check if palindrome of same letter for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if(graph[i][j] == graph[j][i]) { out.println("YES"); for(int k = 0; k <= m; k++) { out.printf("%d ", k % 2 == 0 ? i + 1 : j + 1); } out.println(); return; } } } //Even alternating case for(int i = 0; i < n; i++) { for(int j = 0; j < 2; j++) { if(incoming[i][j] != -1 && outgoing[i][j] != -1) { out.println("YES"); int parity = m / 2 % 2; for(int k = 0; k <= m / 2; k++) { out.printf("%d ", (k + parity) % 2 == 0 ? i + 1 : incoming[i][j] + 1); } for(int k = 0; k < m / 2; k++) { out.printf("%d ", k % 2 == 1 ? i + 1 : outgoing[i][j] + 1); } out.println(); return; } } } out.println("NO"); } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
a84c8fd905422a65aa0d4b2d88152bcd
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
// package com.company; import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class HH4 { static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] Args)throws Exception{ FastReader scan=new FastReader(System.in); int t=1; t=scan.nextInt(); while(t-->0){ int n=scan.nextInt(); int m=scan.nextInt(); String[] edges=new String[n]; for(int i=0;i<n;i++){ edges[i]=scan.next(); } if(n==2||m%2!=0){ if(n==2&&edges[0].charAt(1)==edges[1].charAt(0)){ out.println("YES"); int mode=1; out.print(1+" "); while(m!=0){ out.print((mode+1)+" "); mode=(mode+1)%2; m--; } out.println(); }else{ if(m%2==0){ out.println("NO"); }else{ out.println("YES"); int mode=1; out.print(1+" "); while(m!=0){ out.print((mode+1)+" "); mode=(mode+1)%2; m--; } out.println(); } } }else{ int n1=-1; int n2=-1; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(edges[i].charAt(j)==edges[j].charAt(i)){ n1=i+1; n2=j+1; } } } if(n1!=-1){ out.println("YES"); out.print(n1+" "); int mode=0; while(m!=0){ if(mode==0){ out.print(n2+" "); }else{ out.print(n1+" "); } mode=(mode+1)%2; m--; } out.println(); }else{ out.println("YES"); int c=-1; int ao=-1; int bo=-1; for(int i=0;i<n;i++){ int tao=-1; int tbo=-1; for (int j = 0; j < n; j++) { if (i != j) { if(edges[i].charAt(j)=='a'){ tao=j+1; }else{ tbo=j+1; } } } if(tao!=-1&&tbo!=-1){ c=i+1; ao=tao; bo=tbo; break; } } if(m%4!=0){ out.print(ao+" "); for(int i=1;i<=m/2;i++){ if(i%2==1){ out.print(c+" "+bo+" "); }else{ out.print(c+" "+ao+" "); } } out.println(); }else{ out.print(c+" "); for(int i=1;i<=m/4;i++){ out.print(ao+" "+c+" "); } for(int i=1;i<=m/4;i++){ out.print(bo+" "+c+" "); } out.println(); } } } } out.flush(); out.close(); } static class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
879e94d8f006e4a8a18fcfe7ddc8ad2d
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class d { public static int n; public static int m; public static char[][] g; public static void main(String[] args) throws Exception { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(stdin.readLine()); int nC = Integer.parseInt(tok.nextToken()); for (int loop=0; loop<nC; loop++) { tok = new StringTokenizer(stdin.readLine()); n = Integer.parseInt(tok.nextToken()); m = Integer.parseInt(tok.nextToken()); g = new char[n][]; for (int i=0; i<n; i++) g[i] = stdin.readLine().toCharArray(); go(); } } public static void go() { int[] tmp = twoCycle(); if (tmp != null) { StringBuffer sb = new StringBuffer(); sb.append(""+(tmp[0]+1)); for (int i=1; i<=m; i++) sb.append(" "+(tmp[i%2]+1)); System.out.println("YES"); System.out.println(sb); return; } if (m%2 == 1) { System.out.println("YES"); StringBuffer sb = new StringBuffer(); sb.append("1"); for (int i=1; i<=m; i++) sb.append(" "+((i%2)+1)); System.out.println(sb); return; } // This is impossible. if (n == 2) { System.out.println("NO"); return; } // here m is even and no aa or bb. boolean flag = false; int[] cycle = new int[4]; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { for (int k=0; k<3; k++) { if (i == j || i == k || j == k) continue; if (g[i][j] == g[j][k]) { cycle[0] = i; cycle[1] = j; cycle[2] = k; cycle[3] = j; flag = true; break; } } if (flag) break; } if (flag) break; } if (m%4 == 2) { System.out.println("YES"); StringBuffer sb = new StringBuffer(); sb.append(""+(cycle[0]+1)); for (int i=1; i<=m; i++) sb.append(" "+((cycle[i%4]+1))); System.out.println(sb); return; } System.out.println("YES"); StringBuffer sb = new StringBuffer(); sb.append(""+(cycle[1]+1)); for (int i=2; i<=m+1; i++) sb.append(" "+((cycle[i%4]+1))); System.out.println(sb); return; } public static int[] twoCycle() { for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (i == j) continue; if (g[i][j] == g[j][i]) { return new int[]{i,j}; } } } return null; } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
40ac6d925d40c91a7fdbde4400065c2c
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static long mod = (long) 1e9 + 7; static long inf = (long) 1e16; static int n, m, k; static ArrayList<Integer>[] ad, adA, adB; static int[][][] memo; static boolean vis[]; static long[] f, inv, ncr[]; static HashMap<Integer, Integer> hm; static int[] pre, suf, Smax[], Smin[]; static int idmax, idmin; static ArrayList<Integer> av; static HashMap<Integer, Integer> mm; static boolean[] corr; static int[] lazy[], lazyCount; static int[] a, in; static char[][] g; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { n = sc.nextInt(); m = sc.nextInt(); stack = new Stack<>(); dfs_low = new int[n]; dfs_num = new int[n]; inSCC = new int[n]; Arrays.fill(inSCC, -1); ad = new ArrayList[n]; for (int i = 0; i < n; i++) ad[i] = new ArrayList<>(); g = new char[n][n]; for (int i = 0; i < n; i++) g[i] = sc.nextLine().toCharArray(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (g[i][j] == 'a') { ad[i].add(j); } th = -1; tarjanSCC(); if (th != -1) { ArrayList<Integer> ar = new ArrayList<>(); for (int i = 0; i < n; i++) if (inSCC[i] == th) ar.add(i); adA = new ArrayList[n]; for (int i = 0; i < n; i++) adA[i] = new ArrayList<>(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (g[i][j] == 'a' && inSCC[i] == inSCC[j]) adA[i].add(j); int st = ar.get(0); out.println("YES"); out.print(st + 1); while (m-- > 0) { st = adA[st].get(0); out.print(" " + (st + 1)); } out.println(); continue; } for (int i = 0; i < n; i++) ad[i] = new ArrayList<>(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (g[i][j] == 'b') { ad[i].add(j); } th = -1; stack = new Stack<>(); counter = 0; SCC = 0; dfs_low = new int[n]; dfs_num = new int[n]; inSCC = new int[n]; Arrays.fill(inSCC, -1); tarjanSCC(); if (th != -1) { ArrayList<Integer> ar = new ArrayList<>(); for (int i = 0; i < n; i++) if (inSCC[i] == th) ar.add(i); adA = new ArrayList[n]; for (int i = 0; i < n; i++) adA[i] = new ArrayList<>(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (g[i][j] == 'b' && inSCC[i] == inSCC[j]) adA[i].add(j); int st = ar.get(0); out.println("YES"); out.print(st + 1); while (m-- > 0) { st = adA[st].get(0); out.print(" " + (st + 1)); } out.println(); continue; } if (m % 2 == 1) { out.println("YES"); for (int i = 0; i < m + 1; i++) if (i % 2 == 0) out.print(1 + " "); else out.print(2 + " "); out.println(); } else { int half = m / 2; if (half % 2 == 0) { int node = -1; int first = 0; int second = 0; for (int i = 0; i < n; i++) { first = -1; second = -1; for (int j = 0; j < n; j++) { if (g[i][j] == 'a') first = j; if (g[i][j] == 'b') second = j; } if (first != -1 && second != -1) { node = i; break; } } if (node == -1) out.println("NO"); else { out.println("YES"); out.print(node + 1); for (int i = 0; i < half; i++) if (i % 2 == 0) out.print(" " + (first + 1)); else out.print(" " + (node + 1)); for (int i = half; i < m; i++) if (i % 2 == 0) out.print(" " + (second + 1)); else out.print(" " + (node + 1)); out.println(); } } else { half = m / 2; int[][] all = new int[n][2]; for (int i = 0; i < n; i++) { all[i] = new int[] { -1, -1 }; for (int j = 0; j < n; j++) if (g[i][j] == 'a') all[i][0] = j; else if (g[i][j] == 'b') all[i][1] = j; } int node = -1; int first = -1; int second = 0; for (int i = 0; i < n; i++) { first = -1; second = -1; for (int j = 0; j < n; j++) if (g[i][j] == 'b' && all[j][1] != -1) { first = j; second = all[j][1]; node = i; } for (int j = 0; j < n; j++) if (g[i][j] == 'a' && all[j][0] != -1) { first = j; second = all[j][0]; node = i; } if (node != -1) break; } if (node == -1) out.println("NO"); else { out.println("YES"); out.print(node + 1); for (int i = 0; i < half; i++) if (i % 2 == 0) out.print(" " + (first + 1)); else out.print(" " + (node + 1)); for (int i = half; i < m; i++) if (i % 2 == 0) out.print(" " + (first + 1)); else out.print(" " + (second + 1)); out.println(); } } } } out.close(); } static int th; static int counter, SCC, dfs_num[], dfs_low[]; static int[] inSCC; static Stack<Integer> stack; static void tarjanSCC() // O(V + E) { for (int i = 0; i < n; ++i) if (dfs_num[i] == 0) tarjanSCC(i); } static void tarjanSCC(int u) { dfs_num[u] = dfs_low[u] = ++counter; stack.push(u); for (int v : ad[u]) { if (dfs_num[v] == 0) tarjanSCC(v); if (inSCC[v] == -1) dfs_low[u] = Math.min(dfs_low[u], dfs_low[v]); } if (dfs_num[u] == dfs_low[u]) { // SCC found SCC++; int cc = 0; while (true) { int v = stack.pop(); cc++; inSCC[v] = SCC; if (v == u) break; } if (cc > 1) th = SCC; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
5eacf12a4ac3b989a1276ab3840bed23
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class D { public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); StringBuilder sb = new StringBuilder(); while(T-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); char[][] map = new char[n][n]; for(int i = 0; i < n; i++){ map[i] = sc.next().toCharArray(); } if(n == 2 && m % 2 == 0 && map[0][1] != map[1][0]) { sb.append("NO\n"); } else { sb.append("YES\n"); if(m % 2 == 1) { for(int i = 0; i <= m/2; i++){ sb.append("1 2 "); } sb.replace(sb.length()-1, sb.length(), "\n"); } else { boolean loop = false; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i != j && map[i][j] == map[j][i]) { for(int r = 0; r < m/2; r++){ sb.append(String.format("%d %d ", i+1, j+1)); } sb.append(i+1+"\n"); loop = true; break; } } if(loop) break; } if(!loop) { if(map[0][1] == map[1][2]) { int k = m/2; for(int i = 0; i < k; i++){ if((k-i) % 2 == 1) sb.append("1 "); else sb.append("2 "); } sb.append("2 "); for(int i = 0; i < k; i++){ if(i % 2 == 0) sb.append("3 "); else sb.append("2 "); } sb.replace(sb.length()-1, sb.length(), "\n"); } else if(map[1][2] == map[2][0]) { int k = m/2; for(int i = 0; i < k; i++){ if((k-i) % 2 == 1) sb.append("2 "); else sb.append("3 "); } sb.append("3 "); for(int i = 0; i < k; i++){ if(i % 2 == 0) sb.append("1 "); else sb.append("3 "); } sb.replace(sb.length()-1, sb.length(), "\n"); } else { //map[2][0] == map[0][1] int k = m/2; for(int i = 0; i < k; i++){ if((k-i) % 2 == 1) sb.append("3 "); else sb.append("1 "); } sb.append("1 "); for(int i = 0; i < k; i++){ if(i % 2 == 0) sb.append("2 "); else sb.append("1 "); } sb.replace(sb.length()-1, sb.length(), "\n"); } } } } } PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
f3ed025d78903246a5e94c5c4d19064b
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); w: while (t-- > 0) { int n = sc.nextInt(), k = sc.nextInt(); char[][] arr = new char[n][n]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.next().toCharArray(); } if (k % 2 == 1) { pw.println("YES"); for (int l = 0; l < k + 1; l++) { pw.print((l % 2 == 0 ? 1 : 2) + " "); } pw.println(); continue w; } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (i == j) continue; if (arr[i][j] == arr[j][i]) { pw.println("YES"); for (int l = 0; l < k + 1; l++) { pw.print((l % 2 == 0 ? (i + 1) : (j + 1)) + " "); } pw.println(); continue w; } } } int x = chk(arr); if (x != -1) { pw.println("YES"); int y = 0, z = 0; for (int i = 0; i < arr.length; i++) { if (arr[x][i] == 'a') y = i + 1; if (arr[x][i] == 'b') z = i + 1; } x++; if (k % 4 == 0) { k /= 4; for (int i = 0; i < k; i++) { pw.print(x + " " + y + " " + x + " " + z + " "); } pw.print(x); } else { for (int i = 0; i < k / 2; i++) { pw.print((i % 2 == 0 ? y : x) + " "); } pw.print(x + " "); for (int i = 0; i < k / 2; i++) { pw.print((i % 2 == 0 ? z : x) + " "); } } pw.println(); } else { pw.println("NO"); } } pw.close(); } static int chk(char[][] arr) { boolean[][] valid = new boolean[arr.length][4]; for (int i = 0; i < valid.length; i++) { for (int j = 0; j < valid.length; j++) { if (i == j) continue; valid[i][arr[i][j] - 'a'] = true; } for (int j = 0; j < valid.length; j++) { if (i == j) continue; valid[i][arr[j][i] - 'a' + 2] = true; } } for (int i = 0; i < valid.length; i++) { if (valid[i][0] && valid[i][1] && valid[i][2] && valid[i][3]) return i; } return -1; } public static class pair implements Comparable<pair> { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } public static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) return this.z - other.z; return this.y - other.y; } else { return this.x - other.x; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { 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\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
8b4ba826291717ada73a4996c39b5291
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class codeforces { public static void main(String[] args) throws Exception { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); char[][]a=new char[n][n]; for(int i=0;i<n;i++) { a[i]=sc.next().toCharArray(); } if(n==2) { if(a[0][1]==a[1][0]) { pw.println("YES"); for(int i=0;i<m+1;i++) { pw.print(i%2+1+" "); } pw.println(); }else { if(m%2==1) { pw.println("YES"); for(int i=0;i<m+1;i++) { pw.print(i%2+1+" "); } pw.println(); }else { pw.println("NO"); } } }else { pw.println("YES"); if(m%2==1) { for(int i=0;i<m+1;i++) { pw.print(i%2+1+" "); } pw.println(); }else { char ab=a[0][1]; char bc=a[1][2]; char ca=a[2][0]; int start=0; if(ab==bc) { start=2; }else if(ab==ca) { start=1; }else { start=0; } if(m%3==0) { start=(start+2)%3; }else if(m%3==2) { start=(start+1)%3; } for(int i=0;i<m+1;i++) { pw.print(start+1+" "); start=(start+1)%3; } pw.println(); } } } pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
f186c0cdeab4e10f8a8f8a6b7357b7e2
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Problem699D { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int t = Integer.parseInt(reader.readLine()); for (int tt = 0; tt < t; tt++) { StringTokenizer info = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(info.nextToken()); int m = Integer.parseInt(info.nextToken()); char[][] edges = new char[n][n]; for (int i = 0; i < n; i++) { edges[i] = reader.readLine().toCharArray(); } boolean trivial = false; int trivialIndex1 = -1; int trivialIndex2 = -1; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (edges[i][j] == edges[j][i]) { trivialIndex1 = i; trivialIndex2 = j; trivial = true; break; } } } if (m % 2 == 1) { // loop through arbitrary two vertices trivialIndex1 = 0; trivialIndex2 = 1; trivial = true; } int[] answer = new int[m + 1]; if (trivial) { // loop through index 1 and 2 for (int i = 0; i < m + 1; i++) { answer[i] = i % 2 == 0 ? trivialIndex1 : trivialIndex2; } } else { // find a vertex where outgoing is both a and b int specialVertex = -1; int aVertex = -1; int bVertex = -1; for (int i = 0; i < n; i++) { aVertex = -1; bVertex = -1; for (int j = 0; j < n; j++) { if (i == j) { continue; } if (edges[i][j] == 'a') { aVertex = j; } if (edges[i][j] == 'b') { bVertex = j; } } if (aVertex != -1 && bVertex != -1) { specialVertex = i; break; } } if (specialVertex == -1) { // always possible for n >= 3 I think? answer = null; } else { // loop through aVertex and bVertex if (m % 4 == 0) { // start at special for (int i = 0; i < m / 2; i++) { answer[i] = i % 2 == 0 ? specialVertex : aVertex; } answer[m / 2] = specialVertex; for (int i = 0; i < m / 2; i++) { answer[i + m / 2 + 1] = i % 2 == 0 ? bVertex : specialVertex; } } else { // start at aVertex for (int i = 0; i < m / 2; i++) { answer[i] = i % 2 == 0 ? aVertex : specialVertex; } answer[m / 2] = specialVertex; for (int i = 0; i < m / 2; i++) { answer[i + m / 2 + 1] = i % 2 == 0 ? bVertex : specialVertex; } } } } if (answer == null) { writer.println("NO"); } else { writer.println("YES"); for (int i = 0; i < m; i++) { writer.print(answer[i] + 1); writer.print(' '); } writer.println(answer[m] + 1); } } reader.close(); writer.close(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
64b1ce80136d4b94026398723ead4a2c
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class CFTemplate { static final long MOD = 1000000007L; //static final long MOD2 = 1000000009L; //static final long MOD = 998244353L; //static final long INF = 500000000000L; static final int INF = 100000000; static final int NINF = -100000; static FastScanner sc; static PrintWriter pw; public static void main(String[] args) { sc = new FastScanner(); pw = new PrintWriter(System.out); int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); int M = sc.ni(); boolean[][] adj = new boolean[N][N]; int[] cnt = new int[N]; for (int i = 0; i < N; i++) { String row = sc.next(); for (int j = 0; j < N; j++) { if (row.charAt(j)=='a') adj[i][j] = true; if (adj[i][j]) cnt[i] += 1; //number of 'a's leaving i } } int[] same = null; check: for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j++) { if (adj[i][j]==adj[j][i]) { same = new int[]{i,j}; break check; } } } if (same != null) { pw.println("YES"); for (int i = 0; i <= M; i++) { pw.print((same[i%2]+1) + " "); } pw.println(); continue; } if (M % 2 == 1) { pw.println("YES"); for (int i = 0; i <= M; i++) { pw.print(((i%2)+1) + " "); } pw.println(); continue; } boolean exist = false; for (int j = 0; j < N; j++) { if (cnt[j] > 0 && cnt[j] < N-1) { //answer exists int[] key = null; loop: for (int i = 0; i < N; i++) { for (int k = i+1; k < N; k++) { if (i==j||k==j) continue; if (adj[i][j]==adj[j][k]) { key = new int[]{i,j,k}; break loop; } } } int[] ans = new int[M+1]; for (int x = M/2; x <= M; x++) { if ((x-M/2)%2==0) ans[x] = key[1]; else ans[x] = key[2]; } for (int x = M/2; x >= 0; x--) { if ((M/2-x)%2==0) ans[x] = key[1]; else ans[x] = key[0]; } pw.println("YES"); for (int i = 0; i <= M; i++) { pw.print((ans[i]+1) + " "); } pw.println(); exist = true; break; } } if (!exist) { pw.println("NO"); } } pw.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N, int mod) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni()+mod; return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N, long mod) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl()+mod; return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 8
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
bf49f8375669a03c95a078c0b8377ff7
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
//@author->.....future_me......// //..............Learning.........// /*Compete against yourself*/ import java.util.*; import java.io.*; import java.lang.*; import java.math.BigInteger; public class A { static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { // try { // int t = sc.nextInt(); while (t-- > 0) A.go(); out.flush(); // } catch (Exception e) { // return; // } } static int count = 0; static HashSet<Integer> set = new HashSet<Integer>(); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static void go() { int n=sc.nextInt();int m=sc.nextInt(); char[][] a=new char[n][n]; for(int i=0;i<n;i++) {String s=sc.next(); for(int j=0;j<n;j++) {a[i][j]=s.charAt(j);}} if(m==1) { out.println("YES"); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a[i][j]!='*') { out.println((++i)+" "+(++j)); return; } } } } if(m%2==0) { boolean f=false; int node1=0,node2=0; out:for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a[i][j]!='*') { if(a[i][j]==a[j][i]) { f=true;node1=i;node2=j;break out; } } } } // out.println(node1+" "+node2); node1++;node2++; if(f==true) { out.println("YES"); for(int i=0;i<m+1;i++) {if(i%2==0)out.print(node1+" ");else out.print(node2+" ");} out.println(); }else { // out.println("NO"); // return; node1=-1;node2=-1; boolean ff=false; int node3=-1; out:for(int i=0;i<n;i++) { node3=-1;node2=-1; for(int j=0;j<n;j++) { if(a[i][j]!='*') { if(a[i][j]=='a') { node3=j; } if(a[i][j]=='b')node2=j; } } if(node3>=0&&node2>=0) { ff=true; node1=i; break; } } // out.println(node1+" "+node2+" "+node3); if(ff==true) { out.println("YES"); int xx=m/2; node1++;node2++;node3++;//node1 is y and node2 is x and node3 is z if(xx%2==1) { out.print(node2+" "); m--; } print2(node1,node3,node2,m); return; } out.println("NO"); return; } }else { boolean f=false; boolean ff=false; int node1=0,node2=0; int node11=0,node22=0; out:for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a[i][j]!='*') { if(a[i][j]==a[j][i]) { f=true;node1=i;node2=j;break out; } if((a[i][j]=='a'&&a[j][i]=='b')||(a[i][j]=='b'&&a[j][i]=='a')){ ff=true; node11=i;node22=j;break out; } } } } node1++;node2++; node11++;node22++; if(f==true) { out.println("YES"); for(int i=0;i<m+1;i++) {if(i%2==0)out.print(node1+" ");else out.print(node2+" ");} out.println(); }else if(ff==true) { out.println("YES"); for(int i=0;i<m+1;i++) {if(i%2==0)out.print(node11+" ");else out.print(node22+" ");} out.println(); }else { out.println("NO"); } return; } } static void print2 (int y, int z, int x, int m) { for(int i=0; i<=m; i++) { if(i%2 == 0) out.print((y)+ " "); if(i%4 == 1) out.print((z)+ " "); if(i%4 ==3)out.print((x)+ " "); } out.println(); } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static int prime[] = new int[1000005]; static int N = 1000005; static void sieve() { prime[0] = 1; prime[1] = 1; for (int i = 2; i * i <= N; i++) { if (prime[i] == 0) { for (int j = i * i; j < N; j += i) { prime[j] = 1; } } } } /* * 5 16 9 8 7 7 1 */ static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } private static void sort(int[] a) { ArrayList<Integer> aa = new ArrayList<>(); for (Integer i : a) { aa.add(i); } Collections.sort(aa); for (int i = 0; i < a.length; i++) a[i] = aa.get(i); } static void sort(long[] a) { ArrayList<Long> aa = new ArrayList<>(); for (Long i : a) { aa.add(i); } Collections.sort(aa); for (int i = 0; i < a.length; i++) a[i] = aa.get(i); } static int mod = (int) 1e9 + 7; static long pow(long x, long y) { long res = 1l; while (y != 0) { if (y % 2 == 1) { res = (x * res); } y /= 2; x = (x * x); } return res; } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } class cell { long f; int s; cell(long f, int s) { this.f = f; this.s = s; } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
028b35282e359bb238647271e8d03fa7
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int f,s; Pair(int f,int s) { this.f=f; this.s=s; } } public static void main(String args[]) { FastReader fs=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int tc=fs.nextInt(); while(tc-->0) { int n=fs.nextInt(); int m=fs.nextInt(); char c[][]=new char[n][n]; for(int i=0;i<n;i++) c[i]=fs.nextLine().toCharArray(); int x=-1,y=-1; outer:for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j)continue; if(c[i][j]==c[j][i]) { x=i+1; y=j+1; break outer; } } } if(x!=-1) { pw.println("YES"); for(int i=0;i<=m;i++) { if(i%2==0) pw.print(x+" "); else pw.print(y+" "); } pw.println(); } else { int z=-1; int a[][]=new int[n][2]; for(int i=0;i<n;i++) Arrays.fill(a[i],-1); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j)continue; if(c[i][j]=='a') a[i][0]=j; else a[i][1]=j; } } outer: for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) continue; int temp=c[i][j]-'a'; if(a[j][temp]>=0) { x=i+1; y=j+1; z=a[j][temp]+1; break outer; } } } if(z==-1) { if(m%2==0&&n%2==0) pw.println("NO"); else if(n%2==1&&m%2==0&&m%n!=0) pw.println("NO"); else { pw.println("YES"); ArrayList<Integer> list=new ArrayList<>(); list.add(0); for(int i=1;i<=m;i++) list.add(i%n); for(int i:list) pw.print((i+1)+" "); pw.println(); } } else { ArrayList<Integer> list=new ArrayList<>(); pw.println("YES"); if(m%2!=0) { for(int i=0;i<=m;i++) { if(i%2==0) pw.print(x+" "); else pw.print(y+" "); } } else { boolean start=false; if(m%4!=0) { for(int i=0;i<m/2;i++) { if(i%2==0) { if(!start) { list.add(x); start=true; } list.add(y); list.add(z); } else { list.add(y); list.add(x); } } } else { for(int i=0;i<m/4;i++) { if(!start) { list.add(y); start=true; } list.add(z); list.add(y); list.add(x); list.add(y); } } for(int i:list) pw.print(i+" "); pw.println(); } } } } pw.flush(); pw.close(); } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
1c4f974a7949db58e1c0c583600e5a1d
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
// package com.company; import java.io.File; import java.util.*; public class Main { static int n,m; static List<Integer> result; static boolean makePlindrome(int num1, int num2, int num3, char[][] arr){ result = new ArrayList<Integer>(); for(int k=0;k<(m/2)+1;k++) { if((m/2)%2==0){ if(k%2==0) result.add(num3+1); else result.add(num2+1); } else { if(k%2==0) result.add(num2+1); else result.add(num3+1); } } for(int k=0;k<(m/2);k++) { if(k%2==0) result.add(num1+1); else result.add(num2+1); } StringBuilder sb = new StringBuilder(); int x,y; for(int i=0;i< result.size()-1;i++){ x = result.get(i); y = result.get(i+1); sb.append(arr[x-1][y-1]); } // System.out.println(sb.toString()); boolean is_plindrome = true; for(int i=0;i<(sb.length()/2);i++) { if(sb.charAt(i) != sb.charAt(sb.length()-i-1)) { is_plindrome = false; break; } } if(is_plindrome) { System.out.println("YES"); for(int k=0;k< result.size();k++) if(k+1==result.size()) System.out.println(result.get(k)); else System.out.print(result.get(k)+" "); } return is_plindrome; } static boolean brueForce(char temp, char[][] arr, int i){ int temp_m = m; List<Integer> temp_result = new ArrayList<Integer>(); temp_result.add(i); boolean sol = false; for(int j=i;j<n;j++){ if(temp_m==0) { sol=true; break; } boolean temp_sol = false; for(int k=0;k<n;k++){ if(arr[j][k]==temp){ temp_result.add(j+1); temp_m--; j=k-1; temp_sol=true; break; } } if(temp_sol==false) break; } if(sol){ System.out.println("YES"); for(int k=0;k< temp_result.size();k++) if(k+1==temp_result.size()) System.out.println(temp_result.get(k)); else System.out.print(temp_result.get(k)+" "); } return sol; } public static void main(String[] args) { try{ File file = new File("in.rtf"); Scanner input = null; if(file.exists()) input = new Scanner(file); else input = new Scanner(System.in); //---------------------INPUT------------ int t = input.nextInt(); List<Integer> result; for(int i =0;i<t;i++){ n = input.nextInt(); m= input.nextInt(); result = new ArrayList<Integer>(); char[][] arr = new char[n][n]; for(int j=0;j<n;j++) arr[j] = input.next().toCharArray(); boolean sol = false; for(int j=0;j<n;j++){ int num1=0, num2=0; for(int k=0;k<n;k++){ if(j==k || arr[j][k]=='*') continue; if(arr[j][k]==arr[k][j] || m%2==1) { num1 = j; num2 = k; sol = true; break; } } if(sol){ for(int k=0;k<=m;k++) { if(k%2==0) result.add(num1+1); else result.add(num2+1); } System.out.println("YES"); for(int k=0;k< result.size();k++) if(k+1==result.size()) System.out.println(result.get(k)); else System.out.print(result.get(k)+" "); break; } } if(sol) continue; for(int j=0;j<n;j++){ int num1=0, num2=0, num3=0; for(int k=0;k<n;k++){ if(j==k || arr[j][k]=='*') continue; if(arr[j][k]!=arr[k][j]) { String str1 = arr[j][k]+""+arr[k][j]; // System.out.println(str1+" j: "+j+" k: "+k); for(int r=0;r<n;r++){ if(r==k || r==j || arr[k][r]=='*') continue; String str2 = arr[r][k]+""+arr[k][r]; if(str2.equals(str1)){ num1 = j; num2 = k; num3 = r; if(makePlindrome(num1, num2, num3, arr)){ sol = true; break; } } } if(sol) break; } } if(sol){ break; } } // System.out.println("here"); if(sol) continue; for(int j=0;j<n;j++){ boolean is_sol = false; for(int k=0;k<n;k++){ if(arr[j][k]=='*') continue; if(brueForce(arr[j][k], arr, j+1)) { sol = true; is_sol = true; break; } } if(is_sol) break; } if(sol==false) System.out.println("NO"); } input.close(); } catch (Exception e) { e.printStackTrace(); } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
1cdde3253ea018d83e6c2e1f135a0bb9
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
//package credit; import javax.imageio.metadata.IIOMetadataFormatImpl; import javax.naming.InsufficientResourcesException; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class Main{ static boolean v[]; static int ans[]; int size[]; static int count=0; static int dsu=0; static int c=0; static int e9=1000000007; int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; long max1=Long.MIN_VALUE; long min1=Long.MAX_VALUE; boolean aBoolean=true; boolean y=false; long m=0; static boolean t1=false; 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; } } int parent[]; int rank[]; int n=0; /* 100000 */ ArrayList<ArrayList<Integer>> arrayLists; boolean v1[]; static boolean t2=false; boolean r=false; int fib[]; int fib1[]; int min3=Integer.MAX_VALUE; public static void main(String[] args) throws IOException { Main g = new Main(); g.go(); } public void go() throws IOException { FastReader scanner=new FastReader(); // Scanner scanner = new Scanner(System.in); // BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in)); // String s; PrintWriter printWriter = new PrintWriter(System.out); int t=scanner.nextInt(); for (int i = 0; i < t; i++) { int n=scanner.nextInt(); int m=scanner.nextInt(); int x=0; int y=0; char arr[][]=new char[n][n]; for (int j = 0; j < n; j++) { String s=scanner.next(); arr[j]=s.toCharArray(); } outer:for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if(j!=k&&arr[j][k]==arr[k][j]){ x=j+1; y=k+1; break outer; } } } if(m%2!=0){ printWriter.print("YES"); printWriter.println(); printWriter.print("1 "); for (int j = 0; j <m; j++) { if(j%2==0){ printWriter.print("2"+" "); }else{ printWriter.print("1"+" "); } } printWriter.println(); }else{ if(x!=0&&y!=0){ printWriter.print("YES"); printWriter.println(); printWriter.print(x+" "); for (int j = 0; j < m; j++) { if(j%2==0){ printWriter.print(y+" "); }else{ printWriter.print(x+" "); } } printWriter.println(); }else { int w1 = 0; int x1 = 0; int y1 = 0; int z1 = 0; outer: for (int j = 0; j < n; j++) { int x2=-1; int y2=-1; for (int k = 0; k < n; k++) { if(arr[j][k]=='a'){ x2=k; } else if(arr[j][k]=='b'){ y2=k; } } if(x2!=-1&&y2!=-1){ w1=j+1; x1=x2+1; y1=y2+1; break; } } if(x1!=0&&y1!=0){ printWriter.println("YES"); for(int k = 0;k < m/2;k++){ printWriter.print(((m/2-k) % 2 == 0 ? (w1) : (x1)) + " "); } printWriter.print(w1 + " "); for(int k = 0;k < m/2;k++){ printWriter.print(((k) % 2 == 0 ? (y1) : (w1)) + " " ); } printWriter.println(); } else{ printWriter.println("NO"); } } } } printWriter.flush(); } static final int mod=1_000_000_007; public long mul(long a, long b) { return a*b; } public long fact(int x) { long ans=1; for (int i=2; i<=x; i++) ans=mul(ans, i); return ans; } public long fastPow(long base, long exp) { if (exp==0) return 1; long half=fastPow(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } public long modInv(long x) { return fastPow(x, mod-2); } public long nCk(int n, int k) { return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n-k)))); } public void sieve(int n){ fib=new int[n+1]; fib[1]=-1; fib[0]=-1; for (int i =2; i*i<=n; i++) { if(fib[i]==0) for (int j =i*i; j <=n; j+=i){ fib[j]=-1; // System.out.println("l"); } } } public void parent(int n){ for (int i = 0; i < n; i++) { parent[i]=i; rank[i]=1; size[i]=1; } } public void union(int i,int j){ int root1=find(i); int root2=find(j); // if(root1 != root2) { // parent[root2] = root1; //// sz[a] += sz[b]; // } if(root1==root2){ return; } if(rank[root1]>rank[root2]){ parent[root2]=root1; size[root1]+=size[root2]; } else if(rank[root1]<rank[root2]){ parent[root1]=root2; size[root2]+=size[root1]; } else{ parent[root2]=root1; rank[root1]+=1; size[root1]+=size[root2]; } } public int find(int p){ if(parent[p]!=p){ parent[p]=find(parent[p]); } return parent[p]; // if(parent[p]==-1){ // return -1; // } // else if(parent[p]==p){ // return p; // } // else { // parent[p]=find(parent[p]); // return parent[p]; // } } public double dist(double x1,double y1,double x2,double y2){ double e=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1); double e1=Math.sqrt(e); return e1; } public void make(int p){ parent[p]=p; rank[p]=1; } Random rand = new Random(); public void sort(int[] a, int n) { for (int i = 0; i < n; i++) { int j = rand.nextInt(i + 1); int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } Arrays.sort(a, 0, n); } public long gcd(long a,long b){ if(b==0){ return a; } return gcd(b,a%b); } public void dfs(ArrayList<Integer> arrayLists1){ for (int i = 0; i < arrayLists1.size(); i++) { if(v1[arrayLists1.get(i)]==false){ System.out.println(arrayLists1.get(i)); v1[arrayLists1.get(i)]=true; count++; dfs(arrayLists.get(arrayLists1.get(i))); } } } private void dfs2(ArrayList<Integer>[]arrayList,int j,int count){ ans[j]=count; for(int i:arrayList[j]){ if(ans[i]==-1){ dfs2(arrayList,i,count); } } } private void dfs3(ArrayList<Integer>[] arrayList, int j) { v[j]=true; count++; for(int i:arrayList[j]){ if(v[i]==false) { dfs3(arrayList, i); } } } public double fact(double h){ double sum=1; while(h>=1){ sum=(sum%e9)*(h%e9); h--; } return sum%e9; } public long primef(double r){ long c=0; long ans=1; while(r%2==0){ c++; r=r/2; } if(c>0){ ans*=2; } c=0; // System.out.println(ans+" "+r); for (int i = 3; i <=Math.sqrt(r) ;i+=2) { while(r%i==0){ // System.out.println(i); c++; r=r/i; } if(c>0){ ans*=i; } c=0; } if(r>2){ ans*=r; } return ans; } public long divisor(double r){ long c=0; for (int i = 1; i <=Math.sqrt(r); i++) { if(r%i==0){ if(r/i==i){ c++; } else{ c+=2; } } } return c; } } class Pair{ long x; long y; double z; public Pair(long x,long y){ this.x=x; this.y=y; } // @Override // public int hashCode() { // int hash =27; // return this.x * hash + this.y; // } // @Override // public boolean equals(Object o1){ // if(o1==null||o1.getClass()!=this.getClass()){ // return false; // } // Pair o=(Pair)o1; // if(o.x==this.x&&o.y==this.y){ // return true; // } // return false; // } } class Sorting implements Comparator<Pair> { public int compare(Pair p1,Pair p2){ // if(p1.x==p2.x){ // return -1*Double.compare(p1.y,p2.y); // } // else { return Double.compare(p1.x, p2.x); // } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
b714946553694716d17c6fbdfbdbed40
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static char[][] graph; public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); int t=1; t=f.nextInt(); PrintWriter out=new PrintWriter(System.out); for(int tt=0;tt<t;tt++) { int n=f.nextInt(); int m=f.nextInt(); graph=new char[n][n]; int[][] has=new int[n][2]; for(int i=0;i<n;i++) { has[i][0]=-1; has[i][1]=-1; } for(int i=0;i<n;i++) { char[] curr=f.next().toCharArray(); for(int j=0;j<n;j++) { if(i!=j) { graph[i][j]=curr[j]; if(graph[i][j]=='a') { has[i][0]=j; } else { has[i][1]=j; } } } } boolean temp=false; for(int i=0;i<n;i++) { for(int j=0;j<n && temp==false;j++) { if(graph[i][j]==graph[j][i] && i!=j) { int[] ans= {i+1,j+1}; int curr=0; System.out.println("YES"); for(int k=0;k<=m;k++) { System.out.print(ans[curr]+" "); curr^=1; } System.out.println(); temp=true; break; } } } if(temp) { continue; } if(m%2==1) { int[] ans= {1,2}; int curr=0; System.out.println("YES"); for(int k=0;k<=m;k++) { System.out.print(ans[curr]+" "); curr^=1; } System.out.println(); } else { boolean flag=false; int u=-1; int v=-1; int z=-1; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i!=j) { if(graph[i][j]=='a') { if(has[j][0]==-1) { continue; } else { u=i+1; v=j+1; z=has[j][0]+1; flag=true; break; } } else { if(has[j][1]==-1) { continue; } else { u=i+1; v=j+1; z=has[j][1]+1; flag=true; break; } } } } if(flag) { break; } } if(flag) { System.out.println("YES"); int[] ans= {u,v,z,v}; int curr=1; if(m%4==0) { for(int i=0;i<m+1;i++) { System.out.print(ans[curr%4] +" "); curr++; } System.out.println(); } else { curr=0; for(int i=0;i<m+1;i++) { System.out.print(ans[curr%4]+" "); curr++; } System.out.println(); } } else { System.out.println("NO"); } } } out.close(); } static void sort(int [] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i: a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.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()); } double nextDouble() { return Double.parseDouble(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
e8bd5071b0f1bec3f1cb0b1e0fcbb9d3
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class CF { public static void main(String[] args) { new C().run(); } static class C { Scanner in; public void run() { in = new Scanner(System.in); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(), m = in.nextInt(); char[][] adj = new char[n][n]; for(int i=0; i<n; i++) { char[] s = in.next().toCharArray(); for(int j=0; j<s.length; j++) { adj[i][j] = s[j]; } } if(m%2 == 1) { System.out.println("YES"); System.out.print(1 + " "); for(int i=1; i<m; i+=2) { System.out.print(2 + " " + 1 + " "); } System.out.println(2); } else { int first = -1, second = -1; for(int i=0; i<n; i++) for(int j=0; j<n; j++) { if(i == j) continue; if(adj[i][j] == adj[j][i]) { first = i+1; second = j+1; } } if(first == -1) { int third = -1; for(int i=0; i<n; i++) { char ch = 'z'; for(int j=0; j<n; j++) { if(i==j) continue; if(j == 0) ch = adj[i][j]; else if(adj[i][j] != ch) { first = i+1; second = j+1; for(int k=0; k<j; k++) if(k != i && k!=j) third = k+1; } } } while(third != -1 && adj[first-1][second-1] != adj[second-1][third-1]) { int temp = first; first = second; second = third; third = temp; } if(m%4 == 0 && third != -1) { System.out.println("YES"); int[] cycle = new int[]{second, first, second, third}; for(int i=0; i<=m; i++) { System.out.print(cycle[i%4] + " "); } System.out.println(); } else if (m%4 == 2 && third != -1) { int[] cycle = new int[]{first, second, third, second}; System.out.println("YES"); for(int i=0; i<=m; i++) { System.out.print(cycle[i%4] + " "); } System.out.println(); } else { System.out.println("NO"); } } else { System.out.println("YES"); for(int i=0; i<m; i+=2) { System.out.print(first + " " + second + " "); } System.out.println(first); } } } } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
c3a9a026ac9308b1b8c0703f468e49f0
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public final class D { public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int t = fs.nextInt(); for (int test = 0; test < t; test++) { final int n = fs.nextInt(); final int m = fs.nextInt(); final char[][] g = new char[n][n]; for (int i = 0; i < n; i++) { g[i] = fs.next().toCharArray(); } int sameL = -1; int sameR = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && g[i][j] == g[j][i]) { sameL = i + 1; sameR = j + 1; } } } if (m % 2 != 0) { sameL = 1; sameR = 2; } if (sameL != -1 && sameR != -1) { final StringBuilder sb = new StringBuilder(); boolean turn = true; for (int i = 0; i <= m; i++) { sb.append(turn ? sameR : sameL); sb.append(' '); turn ^= true; } System.out.println("YES"); System.out.println(sb); continue; } int a = -1; int b = -1; int c = -1; for (int i = 0; i < n; i++) { int l = -1; int r = -1; for (int j = 0; j < n; j++) { if (i != j) { if (g[i][j] == 'a') { l = j; } else if (g[i][j] == 'b') { r = j; } } } if (l != -1 && r != -1) { a = i + 1; b = l + 1; c = r + 1; break; } } if (a != -1) { final StringBuilder sb = new StringBuilder(); boolean turn = (m / 2) % 2 == 0; if (!turn) { final int temp = b; b = c; c = temp; } for (int i = 0; i <= m / 2; i++) { sb.append(turn ? a : b); sb.append(' '); turn ^= true; } for (int i = 0; i < m / 2; i++) { sb.append(turn ? a : c); sb.append(' '); turn ^= true; } System.out.println("YES"); System.out.println(sb); continue; } System.out.println("NO"); } } static final class Utils { public static void shuffleSort(int[] x) { shuffle(x); Arrays.sort(x); } public static void shuffleSort(long[] x) { shuffle(x); Arrays.sort(x); } public static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } public static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
a43f0ccb95cece23360c64b14be98616
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public final class D { public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int t = fs.nextInt(); for (int test = 0; test < t; test++) { final int n = fs.nextInt(); final int m = fs.nextInt(); final char[][] g = new char[n][n]; for (int i = 0; i < n; i++) { g[i] = fs.next().toCharArray(); } int sameL = -1; int sameR = -1; outer: for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && g[i][j] == g[j][i]) { sameL = i + 1; sameR = j + 1; break outer; } } } if (m % 2 != 0) { sameL = 1; sameR = 2; } if (sameL != -1 && sameR != -1) { final StringBuilder sb = new StringBuilder(); boolean turn = true; for (int i = 0; i <= m; i++) { if (turn) { sb.append(sameR); } else { sb.append(sameL); } sb.append(' '); turn ^= true; } System.out.println("YES"); System.out.println(sb); continue; } int a = -1; int b = -1; int c = -1; for (int i = 0; i < n; i++) { int l = -1; int r = -1; for (int j = 0; j < n; j++) { if (i != j) { if (g[i][j] == 'a' && g[j][i] == 'b') { l = j + 1; } else if (g[i][j] == 'b' && g[j][i] == 'a') { r = j + 1; } } } if (l != -1 && r != -1) { a = i + 1; b = l; c = r; break; } } if (a != -1) { final StringBuilder sb = new StringBuilder(); boolean turn = (m / 2) % 2 == 0; if (!turn) { final int temp = b; b = c; c = temp; } for (int i = 0; i <= m / 2; i++) { if (turn) { sb.append(a); } else { sb.append(b); } sb.append(' '); turn ^= true; } for (int i = 0; i < m / 2; i++) { if (turn) { sb.append(a); } else { sb.append(c); } sb.append(' '); turn ^= true; } System.out.println("YES"); System.out.println(sb); continue; } System.out.println("NO"); } } static final class Utils { public static void shuffleSort(int[] x) { shuffle(x); Arrays.sort(x); } public static void shuffleSort(long[] x) { shuffle(x); Arrays.sort(x); } public static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } public static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
6cfabc827e9bb52fc2087b1cd237d62f
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
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.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.Objects; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DABGraph solver = new DABGraph(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class DABGraph { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); char[][] arr = in.nextCharMatrix(n, n); if (m % 2 == 1) { out.println("YES"); for (int i = 0; i < m; i += 2) { out.print("1 2 "); } out.println(); return; } if (n == 2) { if (arr[0][1] == arr[1][0]) { out.println("YES"); for (int i = 0; i < m; i += 2) { out.print("1 2 "); } out.println("1"); } else { out.println("NO"); } return; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; if (arr[i][j] == arr[j][i]) { out.println("YES"); for (int k = 0; k < m; k += 2) { out.print((i + 1) + " " + (j + 1) + " "); } out.println((i + 1)); return; } } } for (int i = 0; i < n; i++) { HashMap<Pair, Integer> hm = new HashMap<>(); for (int j = 0; j < n; j++) { if (i == j) continue; Pair p = new Pair(arr[i][j], arr[j][i]); hm.put(p, j); } for (Pair p : hm.keySet()) { if (hm.containsKey(new Pair(p.b, p.a))) { out.println("YES"); int p1 = hm.get(new Pair(p.b, p.a)) + 1, p2 = i + 1, p3 = hm.get(p) + 1; if (m % 4 == 0) { for (int x = 0; x < m; x += 4) { out.print((p2) + " " + p3 + " " + p2 + " " + p1 + " "); } out.println(p2); return; } for (int x = 0; x < m - 2; x += 4) { out.print(p1 + " " + p2 + " " + p3 + " " + p2 + " "); } out.println(p1 + " " + p2 + " " + p3); return; } } } } class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return Objects.hash(a, b); } public boolean equals(Object obj) { Pair that = (Pair) obj; return a == that.a && b == that.b; } public String toString() { return "[" + a + ", " + b + "]"; } } } static class InputReader { BufferedReader reader; 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 char[][] nextCharMatrix(int rows, int cols) { char[][] matrix = new char[rows][cols]; for (int i = 0; i < rows; i++) matrix[i] = next().toCharArray(); return matrix; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println() { writer.println(); } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
1899ed8be5404d315ddb2c0b8cc03ad7
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.io.*; public class asd { static BufferedReader br; static PrintWriter pw; static int inf = (int) 1e9; static long mod = 998244353; static ArrayList<Integer>[] g; static int r; static boolean[] vis; static long[] dist; static ArrayList<Long> first, last; static void permute(int idx, int l, long sum) { if (idx == l) { if (l == n) last.add(sum); else first.add(sum); return; } permute(idx + 1, l, sum + a[idx]); permute(idx + 1, l, sum); } public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException { // br = new BufferedReader(new FileReader(new File("chief.in"))); br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); char[][] a = new char[n][]; for (int i = 0; i < a.length; i++) { a[i] = sc.next().toCharArray(); } int x = -1, y = -1; for (int i = 0; i < a.length && x == -1; i++) { for (int j = i + 1; j < a.length; j++) { if (a[i][j] == a[j][i]) { x = i + 1; y = j + 1; break; } } } if (x != -1) { boolean f = false; pw.println("YES"); pw.print(x + " "); while (m-- > 0) { if (f) pw.print(x + " "); else pw.print(y + " "); f = !f; } pw.println(); } else { if (m % 2 == 1) { pw.println("YES"); boolean f = false; pw.print(1 + " "); while (m-- > 0) { if (f) pw.print(1 + " "); else pw.print(2 + " "); f = !f; } pw.println(); } else { x = -1; y = -1; int z = -1; for (int i = 0; i < a.length; i++) { int outa = -1; int outb = -1; int ina = -1; int inb = -1; for (int j = 0; j < a.length; j++) { if (a[i][j] == 'a') outa = j + 1; if (a[i][j] == 'b') outb = j + 1; } for (int j = 0; j < a.length; j++) { if (a[j][i] == 'a') { ina = j + 1; } if (a[j][i] == 'b' && outb != -1) { inb = j + 1; } } if (ina != -1 && outa != -1) { x = ina; z = i + 1; y = outa; } else if (inb != -1 && outb != -1) { x = inb; z = i + 1; y = outb; } } if (x == -1) { pw.println("NO"); } else { pw.println("YES"); if((m/2) %2 ==0) { pw.print(z + " "); for (int i = 0; i < m; i++) { if (i % 4 == 3 || i % 4 == 1) pw.print(z + " "); else if (i % 4 == 0) pw.print(y + " "); else pw.print(x + " "); } } else { pw.print(x + " "); for (int i = 0; i < m; i++) { if (i % 4 == 0 || i % 4 == 2) pw.print(z + " "); else if (i % 4 == 1) pw.print(y + " "); else pw.print(x + " "); } } pw.println(); } } } } pw.flush(); } static int n, m; static int[] a; static int dx[] = new int[] { -1, 0, 1, 0 }; static int dy[] = new int[] { 0, -1, 0, 1 }; static int[] suffix(char[] s) { int n = s.length; int[] p = new int[n]; int[] c = new int[n]; { // k == 0 pair[] a = new pair[n]; for (int i = 0; i < a.length; i++) { a[i] = new pair(s[i], i); } Arrays.sort(a); for (int i = 0; i < a.length; i++) { p[i] = a[i].y; } c[p[0]] = 0; for (int i = 1; i < a.length; i++) { if (a[i].x == a[i - 1].x) c[p[i]] = c[p[i - 1]]; else c[p[i]] = c[p[i - 1]] + 1; } } int k = 0; while ((1 << k) < n) { suffix[] a = new suffix[n]; for (int i = 0; i < a.length; i++) { a[i] = new suffix(c[i], c[((1 << k) + i) % n], i); } Arrays.sort(a); for (int i = 0; i < a.length; i++) { p[i] = a[i].idx; } c[p[0]] = 0; for (int i = 1; i < a.length; i++) { if (a[i].x == a[i - 1].x && a[i].y == a[i - 1].y) c[p[i]] = c[p[i - 1]]; else c[p[i]] = c[p[i - 1]] + 1; } k++; } return p; } static class suffix implements Comparable<suffix> { int x, y; int idx; public suffix(int a, int b, int i) { x = a; y = b; idx = i; } @Override public int compareTo(suffix o) { // TODO Auto-generated method stub return ("" + x + y).compareTo("" + o.x + o.y); } } static class Edge implements Comparable<Edge> { int node; long cost; Edge(int a, long b) { node = a; cost = b; } public int compareTo(Edge e) { return Long.compare(cost, e.cost); } } static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while (index > 1) { index >>= 1; sTree[index] = sTree[index << 1] + sTree[index << 1 | 1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 + q2; } } static int[] isComposite; static ArrayList<Integer> primes; // generated by sieve static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); if (1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } static double[] memo; static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static double dis(int x, int y, int z, int w) { return Math.sqrt((x - z) * (x - z) + (y - w) * (y - w)); } static int[] nxtarr() throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); int[] a = new int[st.countTokens()]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(st.nextToken()); } return a; } static long[] nxtarrLong() throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); long[] a = new long[st.countTokens()]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(st.nextToken()); } return a; } static class pair implements Comparable<pair> { int x; int y; int idx; public pair(int d, int u) { x = d; y = u; } public pair(int d, int u, int idx) { x = d; y = u; this.idx = idx; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub return x - o.x; } @Override public String toString() { // TODO Auto-generated method stub return x + " " + y; } } static class triple implements Comparable<triple> { int x; int y; int z; public triple(int a, int b, int c) { x = a; y = b; z = c; } @Override public int compareTo(triple o) { // TODO Auto-generated method stub return x - o.x; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
4388e55827097769ca7847148aa2ebb6
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { // static Scanner sc=new Scanner(System.in); // static ArrayList<Integer> al; // static HashMap<Integer, Integer> map=new HashMap<>(); static FastReader sc=new FastReader(); public static void main (String[] args) throws java.lang.Exception { PrintWriter w=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt();int m=sc.nextInt(),o=0,p=0,f=0; String answer="NO"; int[][] dp=new int[n][2]; for(int i=0;i<n;i++){dp[i][0]=-1;dp[i][1]=-1;} int[][] a=new int[n][n]; for(int i=0;i<n;i++){ String s=sc.next(); for(int j=0;j<n;j++){ if(s.charAt(j)=='a'){a[i][j]=1;dp[i][0]=j;} else if(s.charAt(j)=='b'){a[i][j]=2;dp[i][1]=j;} } } if(m%2!=0){ f=0; w.write("YES\n"); for(int i=0;i<=m;i++){ w.write((f+1)+" "); f=f^1; } w.write("\n"); answer="YES"; } else{ for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[i][j]==a[j][i]){ f=0; w.write("YES\n"); for(int l=0;l<=m;l++){ if(f==0)w.write((i+1)+" "); else w.write((j+1)+" "); f=f^1; } w.write("\n"); answer="YES";break; } } if(answer.equals("YES"))break; } if(answer.equals("NO")){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j)continue; if(a[i][j]==1 && dp[j][0]!=-1){ if((m/2)%2==0){ f=0; w.write("YES\n"); w.write((j+1)+" "); for(int l=0;l<m/2;l++){ if(f==0)w.write((dp[j][0]+1)+" "); else w.write((j+1)+" "); f=f^1; } f=0; for(int l=0;l<m/2;l++){ if(f==0)w.write((i+1)+" "); else w.write((j+1)+" "); f=f^1; } w.write("\n"); } else{ f=0; w.write("YES\n"); w.write((i+1)+" "); for(int l=0;l<m/2;l++){ if(f==0)w.write((j+1)+" "); else w.write((i+1)+" "); f=f^1; } f=0; for(int l=0;l<m/2;l++){ if(f==0)w.write((dp[j][0]+1)+" "); else w.write((j+1)+" "); f=f^1; } w.write("\n"); } answer="YES"; break; } else if(a[i][j]==2 && dp[j][1]!=-1){ if((m/2)%2==0){ f=0; w.write("YES\n"); w.write((j+1)+" "); for(int l=0;l<m/2;l++){ if(f==0)w.write((dp[j][1]+1)+" "); else w.write((j+1)+" "); f=f^1; } f=0; for(int l=0;l<m/2;l++){ if(f==0)w.write((i+1)+" "); else w.write((j+1)+" "); f=f^1; } w.write("\n"); } else{ f=0; w.write("YES\n"); w.write((i+1)+" "); for(int l=0;l<m/2;l++){ if(f==0)w.write((j+1)+" "); else w.write((i+1)+" "); f=f^1; } f=0; for(int l=0;l<m/2;l++){ if(f==0)w.write((dp[j][1]+1)+" "); else w.write((j+1)+" "); f=f^1; } w.write("\n"); } answer="YES"; break; } } if(answer.equals("YES"))break; } } } if(answer.equals("NO"))w.write("NO\n"); } w.flush(); w.close(); } } 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\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
8292f2cfd1ca496bf8561777b1cbd243
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.StringTokenizer; public class COVID { static long mod = 998244353 ; static PrintWriter pw; static ArrayList<Integer>[] adjList; static int INF=(int)1e8; static double EPS=1e-9; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t=sc.nextInt(); test: while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); char[][] g=new char[n][n]; for(int i=0;i<n;i++) g[i]=sc.nextLine().toCharArray(); StringBuilder sb=new StringBuilder(); if(n==2) { if(g[0][1]==g[1][0]) { int cur=0; for(int i=0;i<m;i++,cur^=1) sb.append((cur+1)+" "); sb.append((cur+1)); }else if(m%2==0) { pw.println("NO"); continue test; }else { sb.append("1 2 "); for(int i=0;i<m/2;i++) sb.append("1 2 "); } }else { if(g[0][1]==g[1][2]&&g[1][2]==g[2][0]) { for(int i=0;i<m+1;i++) { sb.append((1+i%3)+" "); } }else { int first=-1,sec=-1,third=-1; if(g[0][1]==g[1][0]) { first=1;sec=2; }else if(g[1][2]==g[2][1]) { first=2;sec=3; }else if(g[2][0]==g[0][2]) { first=1;sec=3; } if(first!=-1) { for(int i=0;i<(m+1);i++) sb.append(((i%2==0)?first:sec)+" "); }else { //y from third to first x from first to sec and sec to third if(g[0][1]==g[1][2]) { first=1;sec=2;third=3; }else if(g[1][2]==g[2][0]) { first=2;sec=3;third=1; }else { first=3;sec=1;third=2; } if(m%2==1) { sb.append(first+" "+sec+" "); for(int i=0;i<m/2;i++) { sb.append(first+" "+sec+" "); } // / sb.append(third); }else { String s; if(m%4==0) { sb.append(sec+" "); s=String.format("%d %d %d %d ",third,sec,first,sec); }else { sb.append(first+" "+sec+" "+third+" "); s=String.format("%d %d %d %d ", sec,first,sec,third); } for(int i=0;i<m/4;i++) sb.append(s); } } } } pw.println("YES"); pw.println(sb.toString()); } pw.flush(); } public static long gcd(long a, long b) { if(b==0)return a; return gcd(b,a%b); } static long pow(long p, long e) { long ans = 1; while (e > 0) { if ((e & 1) == 1) ans = ((ans * 1l * p)); e >>= 1; { } p = ((p * 1l * p)); } return ans; } static long powmod(long b, long e, int mod) { long ans = 1; b %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * b) % mod); e >>= 1; b = (int) ((b * 1l * b) % mod); } return ans; } public static long add(long a, long b) { return (a + b) % mod; } public static long sub(long a, long b) { return (a - b + mod) % mod; } public static long mul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static class longPair implements Comparable<longPair> { long x, y; public longPair(long a, long b) { x = a; y = b; } public int compareTo(longPair p) { return (p.x == x) ? ((p.y == y) ? 0 : (y > p.y) ? 1 : -1) : (x > p.x) ? 1 : -1; } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int a, int b) { this.x = a; y = b; } public int compareTo(Pair o) { return (x == o.x) ? ((y > o.y) ? 1 : (y == o.y) ? 0 : -1) : ((x > o.x) ? 1 : -1); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } 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 long[] nextLongArr(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } 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; } if (sb.length() == 18) { res += Long.parseLong(sb.toString()) / f; sb = new StringBuilder("0"); } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } public static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
74cceebdb13b9d861090a1e7de846351
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub FastReader s = new FastReader(); int tc = s.nextInt(); for(int t = 0;t < tc;t++) { int n = s.nextInt() , m = s.nextInt(); char[][] ch = new char[n][n]; for(int i = 0;i < n;i++) { ch[i] = s.next().toCharArray(); } char[][] transpose = new char[n][n]; for(int i = 0;i < n;i++) { for(int j = 0;j < n;j++) transpose[i][j] = ch[j][i]; } // System.out.println(); boolean same = false; int x = 0; int y = 0; for(int i = 0;i < n;i++) { for(int j = 0;j < n;j++) { if(transpose[i][j] == ch[i][j] && ch[i][j] != '*') { same = true; x = i + 1; y = j + 1; break; } } } if(same) { System.out.println("YES"); int val = x; while(m-- >= 0) { System.out.print(val + " "); val = (val == x) ? y : x; } System.out.println(); continue; } if(m % 2 == 1) { int val = 1; System.out.println("YES"); while(m-- >= 0) { System.out.print(val + " "); val = (val == 1) ? 2 : 1; } System.out.println(); continue; } boolean got = false; for(int i = 0;i < n;i++) { int aa = -1; int bb = -1; for(int j = 0;j < n;j++) { if(ch[i][j] == 'a') aa = j; if(ch[i][j] == 'b') bb = j; } if(aa != -1 && bb != -1) { System.out.println("YES"); for(int j = 0;j < m/2;j++) { System.out.print(((m/2 - j)%2 == 0 ? i + 1 : aa + 1) + " "); } System.out.print((i + 1) + " "); for(int j = 0;j < m/2;j++) { System.out.print(((j % 2 == 0) ? (bb + 1) : i + 1) + " "); } System.out.println(); got = true; break; } } if(!got) System.out.println("NO"); // if(m % 2 == 0) { // store3[] arr = new store3[n]; // for(int i = 0;i < n;i++) arr[i] = new store3(); // for(int i = 0;i < n;i++) { // for(int j = i + 1;j < n;j++) { // if(ch[i][j] == 'a') { // arr[i].a = true; // arr[i].ax = j; // } // else { // arr[i].b = true; // arr[i].by = j; // } // } // } // x = -1; // y = -1; // int start = 0; // int end = 0; // int mid = 0; // boolean found = false; // for(int i = 0;i < n;i++) { // for(int j = 0;j < n;j++) { // if(i == j) continue; // if(ch[i][j] == 'a') { // if(arr[j].a) { // x = arr[i].ax; // // i , j , by // found = true; // start = i; // mid = j; // end = x; // break; // } // } // else { // if(arr[j].b) { // // i , j , ax // y = arr[i].by; // found = true; // start = i; // mid = j; // end = y; // break; // } // // } // } // if(found) break; // } // if(x != -1 || y != -1) { // start++; // mid++; // end++; // if((m/2) % 2 == 1) { // System.out.println("YES"); // System.out.print(start + " "); // int prev = 0; // while(m-- > 0) { // if(prev == 0) { // System.out.print(mid + " "); // prev = 1; // } // else if(prev == 2) { // System.out.print(mid + " "); // prev = 3; // } // else if (prev == 1) { // prev = 2; // System.out.print(end + " "); // } // else if(prev == 3) { // System.out.print(start + " "); // prev = 0; // } // } // System.out.println(); // } // else { // System.out.println("YES"); // System.out.print(mid + " "); // int prev = 0; // while(m-- > 0) { // if(prev == 0) { // System.out.print(end + " "); // prev = 1; // } // if(prev == 1) { // System.out.print(mid + " "); // prev = 2; // } // if(prev == 2) { // System.out.print(start + " "); // prev = 3; // } // if(prev == 3) { // System.out.print(mid + " "); // prev = 0; // } // } // System.out.println(); // } // continue; // } // System.out.println("NO"); // } } } public static long nc2(long k) { return (k*(k - 1))/2; } } class store3 { boolean a; boolean b; int ax; int by; } 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\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
6973df4c42bd4e90fec04e423d26e3cb
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class Question4 { 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 int[] readArray(int n) throws IOException { int[] temp =new int[n]; for(int i = 0;i < n;i++) { temp[i] = nextInt(); } return temp; } public ArrayList<Integer> readList(int n) throws IOException { ArrayList<Integer> list = new ArrayList<>(); for(int i = 0;i < n;i++)list.add(nextInt()); return list; } 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(); } } static Scanner sc = new Scanner(System.in); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static boolean bool = false; public static void main(String[] args) throws IOException { int t = sc.nextInt(); for(int p = 0;p < t;p++) { solve(p); } bw.flush(); bw.close(); } public static void solve(int t) throws IOException { int n = sc.nextInt(); int k = sc.nextInt(); //for the get method ArrayList<Integer> alist[], blist[]; alist =new ArrayList[n]; blist = new ArrayList[n]; for(int i = 0;i < n;i++) { alist[i] = new ArrayList<>(); blist[i] = new ArrayList<>(); } char[][] arr = new char[n][n]; for(int i =0;i < n;i++) arr[i] = sc.next().toCharArray(); //forming alist and blist for get for(int i = 0;i < n;i++) { for(int j = 0;j < n;j++) { if(i == j)continue; if(arr[i][j] == 'a')alist[i].add(j); else if(arr[i][j] == 'b')blist[i].add(j); } } for(int i = 0;i < n;i++) { for(int j = 0;j < n;j++) { if(j == i)continue; if(arr[i][j] == arr[j][i]) { printAns(new int[]{i, j}, k); return; } } } //if odd if(k % 2 == 1) { int i = 1; bw.write("YES\n"); while(i <= k + 1) { bw.write(String.valueOf((i % 2)+ 1) + " "); i++; } bw.write("\n"); return; } //k is even.. no two are the same. //4, 8, 12, etc.. if( k % 4 == 0) { //bw.write("here\n"); for(int i = 0;i < n;i++) { if(alist[i].isEmpty() || blist[i].isEmpty())continue; int p1 = 0, p2 = 0; for(Integer ix : alist[i]) {p1 = ix;break;} for(Integer ix : blist[i]) {p2 = ix;break;} printAns(new int[] {i, p1, i, p2}, k); return; } bw.write("NO\n"); return; } //2, 6, 10. etc for(int i = 0;i < n;i++) { for(int j =0;j < n;j++) { if(i == j)continue; //for p int p = -1; char c = arr[i][j]; if(c == 'a')p = get(j,alist); else p = get(j, blist); if(p != -1) { printAns(new int[]{i, j, p, j}, k); return; } } } bw.write("NO\n"); return; } public static void printAns(int[] arr, int k) throws IOException{ k++; bw.write("YES\n"); for(int i = 0;i < k;i++)bw.write(String.valueOf(arr[i % arr.length] + 1) + " "); bw.write("\n"); } public static int get(int i, ArrayList<Integer> list[]) { for(Integer ix : list[i])return ix; return -1; } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output
PASSED
2e2eb5117bc9ccb9ffcc3c1803570417
train_107.jsonl
1612535700
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m &gt; 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); o:while(cases-- > 0) { String[] str = br.readLine().split(" "); int n = Integer.parseInt(str[0]); int m = Integer.parseInt(str[1]); int[][] mat = new int[n][n]; for(int i=0; i<n; i++) { String s = br.readLine(); for(int j=0; j<n; j++) { char ch = s.charAt(j); if(ch == 'a') { mat[i][j] = 1; }else if(ch == 'b') { mat[i][j] = -1; } } } // Try and find aa or bb so we can form any palin boolean foundaa = false; int[] nodes = new int[2]; for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(mat[i][j] == mat[j][i]) { foundaa = true; nodes[0] = i; nodes[1] = j; } } } if(foundaa) { StringBuffer buf = new StringBuffer(); buf.append("YES\n"); buf.append((nodes[0]+1)+" "); int pos = 1; for(int i=0; i<m; i++) { buf.append((nodes[pos]+1)+" "); pos = (pos+1) % 2; } buf.append("\n"); System.out.print(buf); }else { if(n == 2 && m % 2 == 0) { System.out.println("NO"); continue; } if(m % 2 != 0) { nodes[0] = 0; nodes[1] = 1; StringBuffer buf = new StringBuffer(); buf.append("YES\n"); buf.append((nodes[0]+1)+" "); int pos = 1; for(int i=0; i<m; i++) { buf.append((nodes[pos]+1)+" "); pos = (pos+1) % 2; } buf.append("\n"); System.out.print(buf); }else { // find a node where a enters and a leaves m even here int[] triple = new int[3]; for(int i=0; i<n; i++) { ArrayList<Integer> ain = new ArrayList<>(); ArrayList<Integer> aout = new ArrayList<>(); for(int j=0; j<n; j++) { if(i == j) continue; if(mat[j][i] == 1) { ain.add(j); }else { aout.add(j); } } if(!ain.isEmpty() && !aout.isEmpty()) { triple[0] = ain.get(0); triple[1] = i; triple[2] = aout.get(0); break; } } int pos = -1; if((m/2) % 2 == 0) { // start from center pos = 1; }else { pos = 2; } StringBuffer buf = new StringBuffer(); buf.append("YES\n"); buf.append((triple[pos]+1)+" "); for(int i=0; i<m/2; i++) { pos = pos == 2 ? 1 : 2; buf.append((triple[pos]+1)+" "); } pos = 0; for(int i=0; i<m/2; i++) { buf.append((triple[pos]+1)+" "); pos = pos == 0 ? 1 : 0; } buf.append("\n"); System.out.print(buf); } } } } }
Java
["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"]
2 seconds
["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"]
NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.
Java 11
standard input
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
79b629047e674883a9bc04b1bf0b7f09
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.
2,000
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".
standard output