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 | edc5e2c2a131b5f6f925bb7b8121ecf8 | train_001.jsonl | 1417618800 | Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya. | 256 megabytes | import java.io.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.StringTokenizer;
public class div2_281_A implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") == null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Thread(null, new div2_281_A(), "", 128 * (1L << 20)).start();
}
void init() throws FileNotFoundException {
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
time();
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
String readString(String s) throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), s + "\n \t");
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int readInt(String s) throws IOException {
return Integer.parseInt(readString(s));
}
boolean isPrime(int a) throws IOException {
int del = 0;
for (int i = 2; i < Math.sqrt(a) + 2; i++) {
if (a % i == 0) {
del = i;
break;
}
}
if (del > 0) {
return false;
} else return true;
}
void solve() throws IOException {
String h = readString();
String a = readString();
int[] tkh=new int[100];
int[] coh=new int[100];
int[] tka=new int[100];
int[] coa=new int[100];
int n=readInt();
for(int i=0;i<n;i++){
int t = readInt();
boolean com=readString().equals("h");
int num=readInt();
boolean type=readString().equals("y");
if(com){
tkh[num-1]=t;
coh[num-1]+=type?1:2;
if(coh[num-1]==2||coh[num-1]==3){
coh[num-1]=100;
System.out.println(h+" "+num+" "+t);
}
}else{
tka[num-1]=t;
coa[num-1]+=type?1:2;
if(coa[num-1]==2||coa[num-1]==3){
coa[num-1]=100;
System.out.println(a+" "+num+" "+t);
}
}
}
}
}
| Java | ["MC\nCSKA\n9\n28 a 3 y\n62 h 25 y\n66 h 42 y\n70 h 25 y\n77 a 4 y\n79 a 25 y\n82 h 42 r\n89 h 16 y\n90 a 13 r"] | 2 seconds | ["MC 25 70\nMC 42 82\nCSKA 13 90"] | null | Java 7 | standard input | [
"implementation"
] | b1f78130d102aa5f425e95f4b5b3a9fb | The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls. Each of the following n lines contains information about a foul in the following form: first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs; then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player; then goes the player's number m (1 ≤ m ≤ 99); then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute. | 1,300 | For each event when a player received his first red card in a chronological order print a string containing the following information: The name of the team to which the player belongs; the player's number in his team; the minute when he received the card. If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards). | standard output | |
PASSED | d621e80a190dabf400ec0f5e231a0cbc | train_001.jsonl | 1417618800 | Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.*;
import java.math.*;
import java.io.*;
/**
*
* @author magzhan
*/
public class Cf {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
Scanner in = new Scanner(System.in);
String p = in.next();
String q = in.next();
int m = in.nextInt();
StringTokenizer tknzr;
Vector<String> v;
Vector<String> g = new Vector<String>();
String h = "";
Vector<String> t = new Vector<String>();
Vector<String> r = new Vector<String>();
for (int i = 0; i < m; i++) {
String v0 = in.next();
String v1 = in.next();
String v2 = in.next();
String v3 = in.next();
if (v3.equals("r")) {
if (v1.equals("h")) {
String k = p + " " + v2 + " " + v0;
String _k = v1 + " " + v2;
boolean insert = true;
for (int j = 0; j < r.size(); j++) {
if (r.elementAt(j).equals(_k)) {
insert = false;
}
}
if (insert) {
g.add(k);
r.add(_k);
}
} else {
String k = q + " " + v2 + " " + v0;
String _k = v1 + " " + v2;
boolean insert = true;
for (int j = 0; j < r.size(); j++) {
if (r.elementAt(j).equals(_k)) {
insert = false;
}
}
if (insert) {
g.add(k);
r.add(_k);
}
}
} else {
boolean found = false;
boolean insert = true;
for (int j = 0; j < t.size(); j++) {
if (((String) (v1 + " " + v2)).equals(t.elementAt(j))) {
for (int k = 0; k < r.size(); k++) {
if (r.elementAt(k).equals((String) (v1 + " " + v2))) {
insert = false;
break;
}
}
if (insert) {
if (v1.equals("h")) {
g.add(p + " " + v2 + " " + v0);
r.add((String) (v1 + " " + v2));
} else {
g.add(q + " " + v2 + " " + v0);
r.add((String) (v1 + " " + v2));
}
found = true;
break;
}
}
}
if (!found)
t.add(v1 + " " + v2);
// for (int j = 0; j < t.size(); j++) {
// System.out.println(t.elementAt(j));
// }
}
}
for (int i = 0; i < g.size(); i++) {
System.out.println(g.elementAt(i));
}
} catch(Exception ex) {
System.err.println(ex.toString());
}
}
}
| Java | ["MC\nCSKA\n9\n28 a 3 y\n62 h 25 y\n66 h 42 y\n70 h 25 y\n77 a 4 y\n79 a 25 y\n82 h 42 r\n89 h 16 y\n90 a 13 r"] | 2 seconds | ["MC 25 70\nMC 42 82\nCSKA 13 90"] | null | Java 7 | standard input | [
"implementation"
] | b1f78130d102aa5f425e95f4b5b3a9fb | The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls. Each of the following n lines contains information about a foul in the following form: first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs; then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player; then goes the player's number m (1 ≤ m ≤ 99); then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute. | 1,300 | For each event when a player received his first red card in a chronological order print a string containing the following information: The name of the team to which the player belongs; the player's number in his team; the minute when he received the card. If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards). | standard output | |
PASSED | 82a14ba2d09db16400b09d0ec7fb460f | train_001.jsonl | 1417618800 | Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder out = new StringBuilder();
HashMap<Integer, String> mapH = new HashMap<Integer, String>();
HashMap<Integer, String> mapA = new HashMap<Integer, String>();
int[] arrayH = new int[100];
int[] arrayA = new int[100];
String home = in.next();
String away = in.next();
int n = in.nextInt();
int time, player;
String team, card;
for (int i = 0; i < n; i++) {
time = in.nextInt();
team = in.next();
player = in.nextInt();
card = in.next();
if (team.equals("h")) {
mapH.put(player, card);
if (arrayH[player] == 2) {
continue;
} else if (mapH.get(player).equals("r")) {
arrayH[player] = 2;
out.append(home + " " + player + " " + time + "\n");
} else if (mapH.get(player).equals("y")) {
arrayH[player]++;
if (arrayH[player] == 2) {
out.append(home + " " + player + " " + time + "\n");
}
}
} else if (team.equals("a")) {
mapA.put(player, card);
if (arrayA[player] == 2) {
continue;
} else if (mapA.get(player).equals("r")) {
arrayA[player] = 2;
out.append(away + " " + player + " " + time + "\n");
} else if (mapA.get(player).equals("y")) {
arrayA[player]++;
if (arrayA[player] == 2) {
out.append(away + " " + player + " " + time + "\n");
}
}
}
}
System.out.print(out);
}
}
| Java | ["MC\nCSKA\n9\n28 a 3 y\n62 h 25 y\n66 h 42 y\n70 h 25 y\n77 a 4 y\n79 a 25 y\n82 h 42 r\n89 h 16 y\n90 a 13 r"] | 2 seconds | ["MC 25 70\nMC 42 82\nCSKA 13 90"] | null | Java 7 | standard input | [
"implementation"
] | b1f78130d102aa5f425e95f4b5b3a9fb | The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls. Each of the following n lines contains information about a foul in the following form: first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs; then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player; then goes the player's number m (1 ≤ m ≤ 99); then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute. | 1,300 | For each event when a player received his first red card in a chronological order print a string containing the following information: The name of the team to which the player belongs; the player's number in his team; the minute when he received the card. If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards). | standard output | |
PASSED | 65999a7d49af539c0ba6bc9b44b1ff7a | train_001.jsonl | 1417618800 | Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya. | 256 megabytes |
import java.util.HashSet;
import java.util.Scanner;
public class ProblemA {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String home = scan.next();
String away = scan.next();
int fouls = scan.nextInt();
HashSet<String> hasYellow = new HashSet<String>();
HashSet<String> hasRed = new HashSet<String>();
StringBuilder builder = new StringBuilder();
for (int i=0; i<fouls; i++){
int time = scan.nextInt();
String c = scan.next();
int player = scan.nextInt();
String card = scan.next();
if (!hasRed.contains(player+c)){
if (card.equals("r")){
hasRed.add(player+c);
builder = addRed(home, away, builder, time, c, player);
} else {
if (hasYellow.contains(player+c)){
builder = addRed(home, away, builder, time, c, player);
hasRed.add(player+c);
} else {
hasYellow.add(player+c);
}
}
}
}
scan.close();
System.out.println(builder.toString());
}
private static StringBuilder addRed(String home, String away, StringBuilder builder,
int time, String c, int player) {
if (c.equals("h"))
builder = builder.append(home).append(" "+player).append(" "+time+"\n");
else
builder = builder.append(away).append(" "+player).append(" "+time+"\n");
return builder;
}
}
| Java | ["MC\nCSKA\n9\n28 a 3 y\n62 h 25 y\n66 h 42 y\n70 h 25 y\n77 a 4 y\n79 a 25 y\n82 h 42 r\n89 h 16 y\n90 a 13 r"] | 2 seconds | ["MC 25 70\nMC 42 82\nCSKA 13 90"] | null | Java 7 | standard input | [
"implementation"
] | b1f78130d102aa5f425e95f4b5b3a9fb | The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls. Each of the following n lines contains information about a foul in the following form: first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs; then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player; then goes the player's number m (1 ≤ m ≤ 99); then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute. | 1,300 | For each event when a player received his first red card in a chronological order print a string containing the following information: The name of the team to which the player belongs; the player's number in his team; the minute when he received the card. If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards). | standard output | |
PASSED | 95ff969d4ebb64c0474591303fd9c07a | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class e {
static final FS sc = new FS();
static final PrintWriter pw = new PrintWriter(System.out);
static int n, m, n1, n2, n3;
static ArrayDeque<Integer>[] edges;
static int[] col;
static ArrayDeque<Integer> ad0, ad1;
static ArrayList<pair> al;
static int N;
static int[][] dp;
static int[][] best;
public static void main(String[] args) {
n = sc.nextInt();
m = sc.nextInt();
n1 = sc.nextInt();
n2 = sc.nextInt();
n3 = sc.nextInt();
edges = new ArrayDeque[n];
for(int i = 0; i < n; ++i) edges[i] = new ArrayDeque<>();
for(int i = 0; i < m; ++i) {
int a = sc.nextInt() - 1, b = sc.nextInt() - 1;
edges[a].add(b);
edges[b].add(a);
}
// each component must be two colorable
col = new int[n];
Arrays.fill(col, -1);
al = new ArrayList<>();
for(int i = 0; i < n; ++i) {
if(col[i] == -1) {
ad0 = new ArrayDeque<>();
ad1 = new ArrayDeque<>();
if(!dfs(i, 0)) {
System.out.println("NO");
return;
}
al.add(new pair(ad0, ad1));
}
}
N = al.size();
dp = new int[N + 1][n2 + 1];
for(int[] z : dp) Arrays.fill(z, -1);
best = new int[N + 1][n2 + 1];
if(go(0, 0) == 0) {
System.out.println("NO");
return;
}
char[] out = new char[n];
int num = 0;
for(int i = 0; i < N; ++i) {
if(best[i][num] == 0) {
for(int a : al.get(i).ada) out[a] = '2';
num += al.get(i).a;
}
else {
for(int a : al.get(i).adb) out[a] = '2';
num += al.get(i).b;
}
}
for(int i = 0; i < n; ++i) {
if(out[i] == 0) {
if(n1 > 0) {
out[i] = '1';
--n1;
}
else out[i] = '3';
}
}
pw.println("YES");
pw.println(out);
pw.flush();
}
static int go(int idx, int num) {
if(dp[idx][num] != -1) return dp[idx][num];
if(idx == N) return dp[idx][num] = (num == n2 ? 1 : 0);
int take = 0;
if(num + al.get(idx).a <= n2) take = go(idx + 1, num + al.get(idx).a);
int dont = 0;
if(num + al.get(idx).b <= n2) dont = go(idx + 1, num + al.get(idx).b);
if(dont == 1) best[idx][num] = 1;
return dp[idx][num] = take | dont;
}
static boolean dfs(int idx, int c) {
col[idx] = c;
if(c == 0) ad0.add(idx);
else ad1.add(idx);
for(int next : edges[idx]) {
// better be a different color than us
if(col[next] != -1) {
if(col[next] == col[idx]) return false;
}
else {
dfs(next, c ^ 1);
}
}
return true;
}
static class pair{
int a, b;
ArrayDeque<Integer> ada, adb;
pair(ArrayDeque<Integer> aa, ArrayDeque<Integer> bb){
ada = new ArrayDeque<>();
ada.addAll(aa);
adb = new ArrayDeque<>();
adb.addAll(bb);
a = aa.size();
b = bb.size();
}
public String toString() {
return a + " " + b;
}
}
static class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while(!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch(Exception e) {}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 6f768a038f74b709db53c7b5a4655e49 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class D2E {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(bf.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
StringTokenizer st1 = new StringTokenizer(bf.readLine());
int n1 = Integer.parseInt(st1.nextToken());
int n2 = Integer.parseInt(st1.nextToken());
int n3 = Integer.parseInt(st1.nextToken());
Map<Integer, ArrayList<Integer>> graph = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0;i<m;i++){
StringTokenizer st2 = new StringTokenizer(bf.readLine());
int v1 = Integer.parseInt(st2.nextToken());
int v2 = Integer.parseInt(st2.nextToken());
if (graph.containsKey(v1)){
graph.get(v1).add(v2);
}
else{
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(v2);
graph.put(v1, temp);
}
if (graph.containsKey(v2)){
graph.get(v2).add(v1);
}
else{
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(v1);
graph.put(v2, temp);
}
}
for(int i = 1;i<=n;i++){
if (!graph.containsKey(i)){
graph.put(i, new ArrayList<Integer>());
}
}
ArrayList<ArrayList<Set<Integer>>> bipsizes = new ArrayList<ArrayList<Set<Integer>>>();
Set<Integer> seen = new HashSet<Integer>();
boolean ans = true;
int[] depth = new int[n+1];
for(int i = 1;i<=n;i++){
if (!seen.contains(i) && ans == true){
Set<Integer> even = new HashSet<Integer>();
Set<Integer> odd = new HashSet<Integer>();
even.add(i);
seen.add(i);
Queue<Integer> bfs = new LinkedList<Integer>();
bfs.add(i);
depth[i] = 0;
while(!bfs.isEmpty()){
int v = bfs.remove();
for(int k: graph.get(v)){
if (seen.contains(k)){
if ((depth[v]+1)%2 != depth[k]%2){
ans = false;
break;
}
}
else{
if ((depth[v]+1)%2==0){
depth[k] = depth[v]+1;
even.add(k);
seen.add(k);
bfs.add(k);
}
else{
depth[k] = depth[v]+1;
odd.add(k);
seen.add(k);
bfs.add(k);
}
}
}
}
ArrayList<Set<Integer>> temp = new ArrayList<Set<Integer>>();
temp.add(even);
temp.add(odd);
bipsizes.add(temp);
}
}
if (ans == false){
out.println("NO");
}
else{
int[][] dp = new int[bipsizes.size()+1][n2+1];
if (bipsizes.get(0).get(0).size() <= n2)
dp[1][bipsizes.get(0).get(0).size()] = -1;
if (bipsizes.get(0).get(1).size() <= n2)
dp[1][bipsizes.get(0).get(1).size()] = 1;
for(int i = 2;i<=bipsizes.size();i++){
for(int j = 0;j<=n2;j++){
if (dp[i-1][j] != 0){
if (j+bipsizes.get(i-1).get(0).size() <= n2){
dp[i][j+bipsizes.get(i-1).get(0).size()] = -1;
}
if (j+bipsizes.get(i-1).get(1).size() <= n2){
dp[i][j+bipsizes.get(i-1).get(1).size()] = 1;
}
}
}
}
if (dp[bipsizes.size()][n2] == 0){
out.println("NO");
}
else{
Set<Integer> two = new HashSet<Integer>();
for(int i = bipsizes.size();i>0;i--){
if (dp[i][n2] == -1){
n2-=bipsizes.get(i-1).get(0).size();
two.addAll(bipsizes.get(i-1).get(0));
}
else if (dp[i][n2] == 1){
n2-=bipsizes.get(i-1).get(1).size();
two.addAll(bipsizes.get(i-1).get(1));
}
}
Set<Integer> one = new HashSet<Integer>();
Set<Integer> three = new HashSet<Integer>();
int count = 0;
for(int i = 1;i<=n;i++){
if (count == n1)
break;
if (!two.contains(i)){
one.add(i);
count+=1;
}
}
int[] array = new int[4];
out.println("YES");
for(int i = 1;i<=n;i++){
if (one.contains(i)){
array[1]++;
out.print(1);
}
else if (two.contains(i)){
array[2]++;
out.print(2);
}
else{
array[3]++;
out.print(3);
}
}
assert array[1] == n1;
assert array[2] == n2;
assert array[3] == n3;
out.println();
}
}
out.close();
}
}
//
////StringJoiner sj = new StringJoiner(" ");
////sj.add(strings)
////sj.toString() gives string of those stuff w spaces or whatever that sequence is
//class BinaryIndexedTree
//{
// // Max tree size
// final static int MAX = 1000005;
//
// static int BITree[] = new int[MAX];
// /* n --> No. of elements present in input array.
// BITree[0..n] --> Array that represents Binary
// Indexed Tree.
// arr[0..n-1] --> Input array for which prefix sum
// is evaluated. */
//
// // Returns sum of arr[0..index]. This function
// // assumes that the array is preprocessed and
// // partial sums of array elements are stored
// // in BITree[].
// int getSum(int index){
// int sum = 0;
// index = index + 1;
// while(index>0){
// sum += BITree[index];
// index -= index & (-index);
// }
// return sum;
// }
// public static void updateBIT(int n, int index, int val){
// index = index + 1;
// while(index <= n){
// BITree[index] += val;
// index += index & (-index);
// }
// }
// void constructBITree(int arr[], int n){
// for(int i=1; i<=n; i++)
// BITree[i] = 0;
// for(int i = 0; i < n; i++)
// updateBIT(n, i, arr[i]);
// }
//}
| Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | db2a65ed13253580e2e2e92c83efd284 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[1000001]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void print(int[] arr){
for(int i = 0 ;i<arr.length;i++){
System.out.print((arr[i])+" ");
}
System.out.println("");
}
public static void printlist(ArrayList<Integer> arr){
for(int i = 0 ;i<arr.size();i++){
System.out.print((arr.get(i)+1)+" ");
}
System.out.println("");
}
static class node{
int x,y;
ArrayList<Integer> l1,l2;
public node(){
x = 0;y = 0;
l1 = new ArrayList<>();
l2 = new ArrayList<>();
}
}
public static boolean flag = false;
public static void dfs(int index,int start,int[] col,ArrayList<ArrayList<Integer>> conn,node n){
col[index] = start;
if(start==1){
n.l1.add(index);
}else{
n.l2.add(index);
}
for(int next : conn.get(index)){
if(col[next]==0){
dfs(next,(start==1?2:1),col,conn,n);
}else{
if(col[next]==col[index])flag = true;
}
}
}
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int N = sc.nextInt();
int M = sc.nextInt();
int N1 = sc.nextInt();
int N2 = sc.nextInt();
int N3 = sc.nextInt();
ArrayList<ArrayList<Integer>> conn = new ArrayList<>();
for(int i = 0;i<N;i++){
conn.add(new ArrayList<>());
}
for(int i = 0;i<M;i++){
int v1 = sc.nextInt() -1;
int v2 = sc.nextInt() - 1;
conn.get(v1).add(v2);
conn.get(v2).add(v1);
}
ArrayList<node> list = new ArrayList<>();
int[] col = new int[N];
int start = 1;
for(int i = 0;i<N;i++){
if(col[i]==0){
node n = new node();
dfs(i,start,col,conn,n);
n.x = n.l1.size();
n.y = n.l2.size();
list.add(n);
}
}
if(flag){
System.out.println("NO");
}else{
boolean[][] dp = new boolean[5002][list.size()+1];
dp[0][0] = true;
for(int j = 1;j<=list.size();j++){
node n = list.get(j-1);
for(int i = 0;i<5002;i++){
if(i - n.x>=0){
dp[i][j] |= dp[i-n.x][j-1];
}
if(i - n.y>=0){
dp[i][j] |= dp[i-n.y][j-1];
}
}
}
if(!dp[N2][list.size()]){
System.out.println("NO");
}else{
int[] values = new int[N];
for(int j = list.size();j>0;j--){
node n = list.get(j-1);
if(N2-n.x >= 0 && dp[N2-n.x][j-1]){
for(int val : n.l1){
values[val] = 2;
}
N2 -= n.x;
for(int val : n.l2){
if(N1>0){
values[val] = 1;
N1--;
}else{
values[val] = 3;
N3--;
}
}
}else{
for(int val : n.l2){
values[val] = 2;
}
N2 -= n.y;
for(int val : n.l1){
if(N1>0){
values[val] = 1;
N1--;
}else{
values[val] = 3;
N3--;
}
}
}
}
System.out.println("YES");
for(int i : values){
System.out.print(i);
}
}
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 41ac59cbd75b303886ddae47c861eb62 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | //make sure to make new file!
import java.io.*;
import java.util.*;
//wrong, assumes there is only 1 component
public class E87b{
public static ArrayList<ArrayList<Integer>> adj;
public static int[] parity;
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
int n1 = Integer.parseInt(st.nextToken());
int n2 = Integer.parseInt(st.nextToken());
int n3 = Integer.parseInt(st.nextToken());
adj = new ArrayList<ArrayList<Integer>>(n+1);
for(int k = 0; k <= n; k++) adj.add(new ArrayList<Integer>());
for(int k = 0; k < m; k++){
st = new StringTokenizer(f.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
adj.get(a).add(b);
adj.get(b).add(a);
}
parity = new int[n+1];
Arrays.fill(parity,-1);
ArrayList<HashSet<Integer>> a = new ArrayList<HashSet<Integer>>();
ArrayList<HashSet<Integer>> b = new ArrayList<HashSet<Integer>>();
for(int k = 1; k <= n; k++){
if(parity[k] != -1)
continue;
HashSet<Integer> hseta = new HashSet<Integer>();
HashSet<Integer> hsetb = new HashSet<Integer>();
parity[k] = 0;
Queue<Integer> q = new LinkedList<Integer>();
q.add(k);
while(!q.isEmpty()){
int i = q.poll();
if(parity[i] == 0) hseta.add(i);
else hsetb.add(i);
for(int nei : adj.get(i)){
if(parity[nei] == parity[i]) {
out.println("NO");
out.close();
return;
}
if(parity[nei] != -1)
continue;
parity[nei] = 1-parity[i];
q.add(nei);
}
}
a.add(hseta);
b.add(hsetb);
}
int[][] dp = new int[a.size()][n+1];
for(int k = 0; k < a.size(); k++) Arrays.fill(dp[k],Integer.MIN_VALUE);
dp[0][a.get(0).size()] = 1;
dp[0][b.get(0).size()] = 2;
for(int k = 0; k < a.size()-1; k++){
for(int j = 0; j <= n; j++){
if(dp[k][j] == Integer.MIN_VALUE) continue;
//add a, set to 1
dp[k+1][j+a.get(k+1).size()] = 1;
//add b, set to 2
dp[k+1][j+b.get(k+1).size()] = 2;
}
}
if(dp[a.size()-1][n2] == Integer.MIN_VALUE){
out.println("NO");
} else {
HashSet<Integer> two = new HashSet<Integer>();
int x = n2;
for(int k = a.size()-1; k >= 0; k--){
if(dp[k][x] == 1){
for(int i : a.get(k)) two.add(i);
x -= a.get(k).size();
} else {
for(int i : b.get(k)) two.add(i);
x -= b.get(k).size();
}
}
StringJoiner sj = new StringJoiner("");
int ones = 0;
for(int k = 1; k <= n; k++){
if(two.contains(k)){
sj.add("2");
} else {
if(ones < n1){
sj.add("1");
ones++;
} else {
sj.add("3");
}
}
}
out.println("YES");
out.println(sj.toString());
}
out.close();
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 3103aad7b6cc0a74cee96f743c114056 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[1000001]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void print(int[] arr){
for(int i = 0 ;i<arr.length;i++){
System.out.print((arr[i])+" ");
}
System.out.println("");
}
public static void printlist(ArrayList<Integer> arr){
for(int i = 0 ;i<arr.size();i++){
System.out.print((arr.get(i)+1)+" ");
}
System.out.println("");
}
static class node{
int x,y;
ArrayList<Integer> l1,l2;
public node(){
x = 0;y = 0;
l1 = new ArrayList<>();
l2 = new ArrayList<>();
}
}
public static boolean flag = false;
public static void dfs(int index,int start,int[] col,ArrayList<ArrayList<Integer>> conn,node n){
col[index] = start;
if(start==1){
n.l1.add(index);
}else{
n.l2.add(index);
}
for(int next : conn.get(index)){
if(col[next]==0){
dfs(next,(start==1?2:1),col,conn,n);
}else{
if(col[next]==col[index])flag = true;
}
}
}
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int N = sc.nextInt();
int M = sc.nextInt();
int N1 = sc.nextInt();
int N2 = sc.nextInt();
int N3 = sc.nextInt();
ArrayList<ArrayList<Integer>> conn = new ArrayList<>();
for(int i = 0;i<N;i++){
conn.add(new ArrayList<>());
}
for(int i = 0;i<M;i++){
int v1 = sc.nextInt() -1;
int v2 = sc.nextInt() - 1;
conn.get(v1).add(v2);
conn.get(v2).add(v1);
}
ArrayList<node> list = new ArrayList<>();
int[] col = new int[N];
int start = 1;
for(int i = 0;i<N;i++){
if(col[i]==0){
node n = new node();
dfs(i,start,col,conn,n);
n.x = n.l1.size();
n.y = n.l2.size();
list.add(n);
}
}
if(flag){
System.out.println("NO");
}else{
boolean[][] dp = new boolean[5002][list.size()+1];
dp[0][0] = true;
for(int j = 1;j<=list.size();j++){
node n = list.get(j-1);
for(int i = 0;i<5002;i++){
if(i - n.x>=0){
dp[i][j] |= dp[i-n.x][j-1];
}
if(i - n.y>=0){
dp[i][j] |= dp[i-n.y][j-1];
}
}
}
if(!dp[N2][list.size()]){
System.out.println("NO");
}else{
int[] values = new int[N];
for(int j = list.size();j>0;j--){
node n = list.get(j-1);
if(N2-n.x >= 0 && dp[N2-n.x][j-1]){
for(int val : n.l1){
values[val] = 2;
}
N2 -= n.x;
for(int val : n.l2){
if(N1>0){
values[val] = 1;
N1--;
}else{
values[val] = 3;
N3--;
}
}
}else{
for(int val : n.l2){
values[val] = 2;
}
N2 -= n.y;
for(int val : n.l1){
if(N1>0){
values[val] = 1;
N1--;
}else{
values[val] = 3;
N3--;
}
}
}
}
System.out.println("YES");
for(int i : values){
System.out.print(i);
}
}
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | c546b3fb1753914cdb88dd0906b046f5 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class tr1 {
static PrintWriter out;
static StringBuilder sb;
static int n, m, k, ones, zeros;
static long mod = 998244353;
static Boolean[][] memo;
static String s;
static ArrayList<Integer>[] ad;
static long inf = Long.MAX_VALUE;
static int N = 1 << 20 + 1;
static int[] color;
static ArrayList<Integer> o, z;
static int[] ans, head;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
n = sc.nextInt();
m = sc.nextInt();
ad = new ArrayList[n];
for (int i = 0; i < n; i++)
ad[i] = new ArrayList<>();
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int n3 = sc.nextInt();
color = new int[n];
o = new ArrayList<>();
z = new ArrayList<>();
Arrays.fill(color, -1);
ans = new int[n];
head = new int[n];
for (int i = 0; i < m; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
ad[a].add(b);
ad[b].add(a);
}
for (int i = 0; i < n; i++) {
if (color[i] == -1) {
zeros = 0;
ones = 0;
color[i] = 0;
if (!bi(i)) {
System.out.println("NO");
return;
}
head[o.size()] = i;
o.add(ones);
z.add(zeros);
}
}
// System.out.println(o+" "+z);
//System.out.println(Arrays.toString(head));
memo = new Boolean[o.size()][n2 + 1];
if (!dp(0, n2)) {
System.out.print("NO");
return;
}
vis = new boolean[n];
out.println("YES");
trace(0, n2);
// System.out.println(Arrays.toString(ans));
for (int i = 0; i < n; i++) {
if (ans[i] == 0) {
if (n1 == 0)
out.print(3);
else {
n1--;
out.print(1);
}
} else
out.print(ans[i]);
}
out.flush();
}
static void trace(int i, int left) {
if (left < 0)
return;
if (i == o.size()) {
return;
}
// System.out.println(left+" le");
if (dp(i + 1, left - o.get(i))) {
get(head[i], 1);
trace(i + 1, left - o.get(i));
// System.out.println(i+" o");
return;
} else {
get(head[i], 0);
// System.out.println(i+" ");
trace(i + 1, left - z.get(i));
}
}
static boolean dp(int i, int left) {
if (left < 0)
return false;
if (i == o.size()) {
if (left == 0)
return true;
return false;
}
if (memo[i][left] != null)
return memo[i][left];
boolean f = false;
f |= dp(i + 1, left - o.get(i));
f |= dp(i + 1, left - z.get(i));
return memo[i][left] = f;
}
static boolean[] vis;
static void get(int u, int c) {
if (color[u] == c)
ans[u] = 2;
vis[u] = true;
for (int v : ad[u]) {
if (!vis[v])
get(v, c);
}
}
static boolean bi(int u) {
if (color[u] == 0)
zeros++;
else
ones++;
for (int v : ad[u]) {
if (color[v] == color[u])
return false;
if (color[v] == -1) {
color[v] = 1 ^ color[u];
if (!bi(v))
return false;
}
}
return true;
}
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 | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | e56000b58ebcb5b9ff24ff0899abc4ed | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Mufaddal Naya
*/
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);
EGraphColoring solver = new EGraphColoring();
solver.solve(1, in, out);
out.close();
}
static class EGraphColoring {
ArrayList<Integer>[] adj;
HashSet<Integer>[] bip;
int[] clr;
boolean ok = true;
public void solve(int testNumber, InputReader c, OutputWriter w) {
int n = c.readInt(), m = c.readInt();
int n1 = c.readInt(), n2 = c.readInt(), n3 = c.readInt();
adj = c.readGraph(n, m);
ArrayList<HashSet<Integer>> cmp[] = new ArrayList[2];
cmp[0] = new ArrayList<>();
cmp[1] = new ArrayList<>();
clr = new int[n];
Arrays.fill(clr, -1);
ArrayList<Pair<Integer, Integer>> pp = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (clr[i] == -1) {
bip = new HashSet[2];
bip[0] = new HashSet<>();
bip[1] = new HashSet<>();
clr[i] = 0;
dfs(i);
if (ok) {
pp.add(new Pair<>(bip[0].size(), bip[1].size()));
cmp[0].add(bip[0]);
cmp[1].add(bip[1]);
} else {
w.printLine("NO");
return;
}
}
}
int k = pp.size();
boolean dp[][] = new boolean[k + 1][n2 + 1];
dp[0][0] = true;
for (int i = 1; i <= k; i++) {
int t = pp.get(i - 1).first, q = pp.get(i - 1).second;
for (int j = t; j <= n2; j++) {
dp[i][j] = dp[i - 1][j - t];
}
for (int j = q; j <= n2; j++) {
dp[i][j] = dp[i][j] | dp[i - 1][j - q];
}
}
if (!dp[k][n2]) {
w.printLine("NO");
return;
}
int res[] = new int[k + 1];
int j = n2;
for (int i = k; i > 0; i--) {
int t = pp.get(i - 1).first, q = pp.get(i - 1).second;
if (j - t >= 0 && dp[i - 1][j - t]) {
res[i] = 0;
j = j - t;
} else {
res[i] = 1;
j = j - q;
}
}
char ans[] = new char[n];
for (int i = 1; i <= k; i++) {
for (int xx : cmp[res[i]].get(i - 1)) {
ans[xx] = '2';
}
}
for (int i = 0; i < n; i++) {
if (ans[i] != '2') {
if (n1 > 0) {
ans[i] = '1';
n1--;
} else {
ans[i] = '3';
}
}
}
w.printLine("YES");
w.printLine(new String(ans));
}
private void dfs(int v) {
bip[clr[v]].add(v);
for (int u : adj[v]) {
if (clr[u] == -1) {
clr[u] = clr[v] ^ 1;
dfs(u);
} else if (clr[u] == clr[v]) {
ok = false;
}
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public ArrayList<Integer>[] readGraph(int n, int m) {
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = readInt() - 1, v = readInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) &&
!(second != null ? !second.equals(pair.second) : pair.second != null);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) first).compareTo(o.first);
if (value != 0) {
return value;
}
return ((Comparable<V>) second).compareTo(o.second);
}
}
}
| Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | caabafcd7f90bb5f9931849a9f229df5 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 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.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Mufaddal Naya
*/
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);
EGraphColoring solver = new EGraphColoring();
solver.solve(1, in, out);
out.close();
}
static class EGraphColoring {
ArrayList<Integer>[] adj;
HashSet<Integer>[] bip;
boolean[] vis;
public void solve(int testNumber, InputReader c, OutputWriter w) {
int n = c.readInt(), m = c.readInt();
int n1 = c.readInt(), n2 = c.readInt(), n3 = c.readInt();
adj = c.readGraph(n, m);
ArrayList<HashSet<Integer>[]> cmp = new ArrayList<>();
vis = new boolean[n];
ArrayList<Pair<Integer, Integer>> pp = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!vis[i]) {
bip = new HashSet[2];
bip[0] = new HashSet<>();
bip[1] = new HashSet<>();
bip[0].add(i);
vis[i] = true;
if (dfs_(i, 0)) {
pp.add(new Pair<>(bip[0].size(), bip[1].size()));
cmp.add(bip);
} else {
w.printLine("NO");
return;
}
}
}
int k = pp.size();
boolean dp[][] = new boolean[k + 1][n2 + 1];
dp[0][0] = true;
for (int i = 1; i <= k; i++) {
int t = pp.get(i - 1).first, q = pp.get(i - 1).second;
for (int j = t; j <= n2; j++) {
dp[i][j] = dp[i - 1][j - t];
}
for (int j = q; j <= n2; j++) {
dp[i][j] = dp[i][j] | dp[i - 1][j - q];
}
}
if (!dp[k][n2]) {
w.printLine("NO");
return;
}
int res[] = new int[k + 1];
int j = n2;
for (int i = k; i > 0; i--) {
int t = pp.get(i - 1).first, q = pp.get(i - 1).second;
if (j - t >= 0 && dp[i - 1][j - t]) {
res[i] = 0;
j = j - t;
} else {
res[i] = 1;
j = j - q;
}
}
char ans[] = new char[n];
for (int i = 1; i <= k; i++) {
for (int xx : cmp.get(i - 1)[res[i]]) {
ans[xx] = '2';
}
}
for (int i = 0; i < n; i++) {
if (ans[i] != '2') {
if (n1 > 0) {
ans[i] = '1';
n1--;
} else {
ans[i] = '3';
}
}
}
w.printLine("YES");
w.printLine(new String(ans));
}
private boolean dfs_(int x, int par) {
for (int xx : adj[x]) {
if (!vis[xx]) {
bip[par ^ 1].add(xx);
vis[xx] = true;
if (!dfs_(xx, par ^ 1)) {
return false;
}
} else {
if (bip[par].contains(xx)) {
return false;
}
}
}
return true;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public ArrayList<Integer>[] readGraph(int n, int m) {
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = readInt() - 1, v = readInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) &&
!(second != null ? !second.equals(pair.second) : pair.second != null);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) first).compareTo(o.first);
if (value != 0) {
return value;
}
return ((Comparable<V>) second).compareTo(o.second);
}
}
}
| Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 770520352e61ce3ee2ca39bec78458ac | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main {
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception{ }
void solve(int TC) throws Exception{
int n = ni(), m = ni();
int n1 = ni(), n2 = ni(), n3 = ni();
int[] from = new int[m], to = new int[m];
for(int i = 0; i< m; i++){
from[i] = ni()-1;
to[i] = ni()-1;
}
int[][] g = make(n, from, to, m, true);
int[] col = new int[n];
int[] comp = new int[n];
int cmp = 0;
boolean bi = true;
Arrays.fill(col, -1);
ArrayList<Integer>[] list = new ArrayList[n];
for(int i = 0; i< n; i++){
if(col[i] == -1){
list[cmp] = new ArrayList<>();
col[i] = 1;
comp[i] = cmp;
bi &= color(list[cmp], g, col, comp, i, cmp);
cmp++;
}
}
if(!bi)pn("NO");
else{
int[][] cnt = new int[cmp][2];
for(int i = 0; i< cmp; i++)
for(int v:list[i])
cnt[i][col[v]]++;
boolean[][] DP = new boolean[1+cmp][1+n];
DP[0][0] = true;
for(int i = 0; i< cmp; i++){
for(int j = 0; j<= n; j++){
if(DP[i][j]){
DP[i+1][j+cnt[i][0]] = true;
DP[i+1][j+cnt[i][1]] = true;
}
}
}
if(DP[cmp][n2]){
int count = n2;
int[] ans = new int[n];
for(int i = cmp-1; i>= 0; i--){
if(count >= cnt[i][0] && DP[i][count-cnt[i][0]]){
int c = 0;
for(int v:list[i]){
if(col[v] == 0) {
ans[v] = 2;c++;
}
}
hold(cnt[i][0] == c);
count -= cnt[i][0];
}else{
hold(DP[i][count-cnt[i][1]]);
int c = 0;
for(int v:list[i]){
if(col[v] == 1){
ans[v] = 2;
c++;
}
}
hold(c == cnt[i][1]);
count -= cnt[i][1];
}
}
hold(count == 0);
for(int i = 0; i< n; i++){
if(ans[i] == 0){
if (n1 > 0) {
n1--;ans[i] = 1;
}else ans[i] = 3;
}
}
pn("YES");
for(int i:ans)p(i);pn("");
}else pn("NO");
}
}
boolean color(ArrayList<Integer> list, int[][] g, int[] col, int[] comp, int u, int cmp){
boolean valid = true;
list.add(u);
for(int v:g[u]){
if(col[v] == -1){
comp[v] = cmp;
col[v] = col[u]^1;
valid &= color(list, g, col, comp, v, cmp);
}else
valid &= col[u]+col[v] == 1;
}
return valid;
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
static void debug(Object... o){System.out.println(Arrays.deepToString(o));}
final long IINF = (long)2e18;
final int INF = (int)1e9+2;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
static boolean multipleTC = false, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("people.in");
out = new PrintWriter("people.out");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = multipleTC? ni():1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println(System.currentTimeMillis() - ct);
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
int[][] make(int n, int[] from, int[] to, int e, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int[] from, int[] to, int e, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i};
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | cf5f1b03173fe403f052adb4c852b6ac | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
static class Node{
int idx,s1,s2;
public Node(int idx,int s1,int s2){
this.idx=idx;
this.s1=s1;
this.s2=s2;
}
}
static int ans[],s1,s2,cnt;
static Node node[];
static boolean dp[][];
static ArrayList<Integer> adj[];
public static void main(String args[]) throws IOException{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int n1=sc.nextInt();
int n2=sc.nextInt();
int n3=sc.nextInt();
dp=new boolean[5005][5005];
ans=new int[5005];
adj=new ArrayList[n+1];
for(int i=0;i<n+1;i++)adj[i]=new ArrayList<Integer>();
for(int i=0;i<m;i++){
int u=sc.nextInt();
int v=sc.nextInt();
adj[u].add(v);adj[v].add(u);
}
node=new Node[5005];
dp[0][0]=true;
for(int i=1;i<=n;i++){
if(ans[i]==0){
s1=0;s2=0;
dfs(i,1);
node[++cnt]=new Node(i,s1,s2);
for(int j=0;j<=n;j++){
if(j>=s1&&dp[cnt-1][j-s1])dp[cnt][j]=true;
if(j>=s2&&dp[cnt-1][j-s2])dp[cnt][j]=true;
}
}
}
if(!dp[cnt][n2]){
System.out.println("NO");
System.exit(0);
}
ans=new int[5005];
for(int i=cnt;i>=1;i--){
int j=node[i].idx,s1=node[i].s1,s2=node[i].s2;
if(n2>=s1&&dp[i-1][n2-s1]){
n2-=s1;
dfs(j,2);
}else{
n2-=s2;
dfs(j,1);
}
}
for(int i=1;i<=n;i++)if(ans[i]==1&&n3>0){
ans[i]=3;n3--;
}
System.out.println("YES");
for(int i=1;i<=n;i++)System.out.print(ans[i]);
}
public static void dfs(int u,int col){
ans[u]=col;
if(col==1)++s1;else ++s2;
for(int v:adj[u]){
if(ans[v]==0){
dfs(v,3-col);
}else if(ans[v]==col){
System.out.println("NO");
System.exit(0);
}
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 847c4305f7ff7d44c4e8bc720c0aab93 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sol{
static class pair {
int x;
int y;
int id;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static boolean tot[][];
public static int n,m,odd;
public static List<Integer> adj[];
public static int color[] = new int[3];
public static int vis[];
public static boolean used[];
public static pair comp[];
public static int par[];
public static int ans[];
public static boolean poss = true;
public static void main(String[] args) throws IOException{
FastIO sc = new FastIO(System.in);
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
m = sc.nextInt();
vis = new int[n];
ans = new int[n];
used = new boolean[n];
Arrays.fill(vis, -1);
adj = new ArrayList[n];
for(int i=0; i<n; ++i) {
adj[i] = new ArrayList<>();
}
color[0] = sc.nextInt();
color[1] = sc.nextInt();
color[2] = sc.nextInt();
for(int i=0; i<m; ++i) {
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
adj[a].add(b);
adj[b].add(a);
}
int forest = 0;
for(int i=0; i<n; ++i) {
if(vis[i]!=-1) continue;
DFS(i, 0);
forest++;
}
tot = new boolean[color[1]+1][forest+1];
comp = new pair[forest];
par = new int[forest];
for(int i=0; i<forest; ++i) {
comp[i] = new pair(0, 0);
}
if(!poss) {
System.out.println("NO");
System.exit(0);
}
forest = 0;
for(int i=0; i<n; ++i) {
if(used[i])continue;
getVal(forest, i);
forest++;
}
Arrays.fill(used, false);
tot[color[1]][0] = true;
for(int k=0; k<forest; ++k) {
//System.out.println(k);
//System.out.println(comp[k].x + " " + comp[k].y);
for(int i=0; i<color[1]+1; ++i) {
if(tot[i][k]) {
int nxt = i-comp[k].x;
if(nxt>=0)tot[nxt][k+1] = true;
nxt = i-comp[k].y;
if(nxt>=0)tot[nxt][k+1] = true;;
}
}
}
if(!(tot[0][forest])) {
System.out.println("NO");
System.exit(0);
}
int curr = 0;
for(int i=forest-1; i>=0; --i) {
//System.out.println(comp[i].x + " " + comp[i].y);
if(curr+comp[i].x<=color[1]&&tot[curr+comp[i].x][i]) {
par[i] = 0;
curr = curr+comp[i].x;
//System.out.println(0);
continue;
}else {
//System.out.println("HI");
curr = curr+comp[i].y;
par[i] = 1;
//System.out.println(1);
continue;
}
}
int idx = 0;
for(int i=0; i<n; ++i) {
if(used[i])continue;
finalGet(i, par[idx]);
idx++;
}
out.println("YES");
for(int i=0; i<n; ++i) {
out.print(ans[i]);
}
out.println();
out.close();
}
public static void finalGet(int curr, int parity) {
used[curr] = true;
if(parity==0) {
if(vis[curr]==1&&odd<color[0]) {
ans[curr] = 1;
odd++;
}else if(vis[curr]==1) {
ans[curr] = 3;
}else {
ans[curr] = 2;
}
}else {
if(vis[curr]==0&&odd<color[0]) {
ans[curr] = 1;
odd++;
}else if(vis[curr]==0) {
ans[curr] = 3;
}else {
ans[curr] = 2;
}
}
for(int i:adj[curr]) {
if(used[i])continue;
finalGet(i, parity);
}
}
public static void getVal(int k, int curr) {
//System.out.println("HI");
used[curr] = true;
if(vis[curr]==0) {
comp[k].x++;
}else {
comp[k].y++;
}
for(int i: adj[curr]) {
if(used[i]) continue;
getVal(k, i);
}
}
public static void DFS(int curr, int parity) {
vis[curr] = parity;
for(int i : adj[curr]) {
if(parity==0) {
if(vis[i]==0) {
poss = false;
}else if(vis[i]==-1) {
DFS(i, 1);
}
}else {
if(vis[i]==1) {
poss = false;
}else if(vis[i]==-1) {
DFS(i, 0);
}
}
}
}
static class FastIO {
// Is your Fast I/O being bad?
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 6e8e6d35debd45faa2a4f84d04b222b0 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | // package CodeForces;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.LinkedList;
public class EducationalRound87E {
public static LinkedList<Integer>[] adj;
public static int[] visited;
public static boolean dfs(int curr, int color) {
visited[curr] = color;
int next_color = color == 1 ? 2 : 1;
boolean ok = true;
for(Integer x : adj[curr]) {
if(visited[x] == 0) {
ok &= dfs(x, next_color);
}else if(visited[x] != next_color) {
return false;
}else {
continue;
}
}
return ok;
}
public static boolean bipartiteCheck() {
int n = adj.length;
visited = new int[n];
boolean ok = true;
for(int i = 0; i < n; i++) {
if(visited[i] == 0) {
ok &= dfs(i, 1);
}
}
return ok;
}
public static boolean[] type;
public static int[] comp;
public static int[] bfs(int start, int comp_number) {
int[] ans = new int[2];
LinkedList<Integer> q = new LinkedList<Integer>();
int level = 0;
q.add(start);
visited[start] = 1;
ans[0] = 1;
comp[start] = comp_number;
level++;
while(!q.isEmpty()) {
LinkedList<Integer> temp = new LinkedList<Integer>();
while(!q.isEmpty()) {
int top = q.removeFirst();
comp[top] = comp_number;
for(Integer x : adj[top]) {
if(visited[x] == 0) {
visited[x] = 1;
temp.add(x);
type[x] = level == 1;
}
}
}
ans[level] += temp.size();
level = level ^ 1;
q = temp;
}
return ans;
}
public static ArrayList<int[]> bfsUtil(){
int comp_number = 0;
int n = adj.length;
comp = new int[n];
type = new boolean[n];
visited = new int[n];
ArrayList<int[]> ans = new ArrayList<>();
for(int i = 0; i < n; i++) {
if(visited[i] == 0) {
int[] current = bfs(i, comp_number++);
ans.add(current);
}
}
return ans;
}
public static void solve() {
int n = s.nextInt();
int m = s.nextInt();
adj = new LinkedList[n];
for(int i = 0; i < n; i++) {
adj[i] = new LinkedList<Integer>();
}
int n1 = s.nextInt();
int n2 = s.nextInt();
int n3 = s.nextInt();
for(int i = 0; i < m; i++) {
int u = s.nextInt() - 1;
int v = s.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
boolean ok = bipartiteCheck();
if(!ok) {
out.println("NO");
return;
}
ArrayList<int[]> values = bfsUtil();
int n_comp = values.size();
boolean[][] possible = new boolean[n_comp][5001];
int[] first = values.get(0);
possible[0][first[0]] = possible[0][first[1]] = true;
for(int i = 1; i < n_comp; i++) {
int[] now = values.get(i);
for(Integer x : now) {
for(int j = 0; j <= 5000; j++) {
if(possible[i - 1][j]) {
possible[i][j + x] = true;
}
}
}
}
if(possible[n_comp - 1][n2]) {
out.println("YES");
boolean[] comp_type = new boolean[n_comp];
// now backtrack
int curr_ans = n2;
for(int i = n_comp - 1; i >= 1; i--) {
int[] now = values.get(i);
int up = 0;
for(Integer x : now) {
if(curr_ans - x >= 0 && possible[i - 1][curr_ans - x]) {
curr_ans = curr_ans - x;
comp_type[i] = up == 1;
break;
}
up++;
}
}
if(first[1] == curr_ans) {
comp_type[0] = true;
}
int[] ans = new int[n];
for(int i = 0; i < n; i++) {
int my_com = comp[i];
if(comp_type[my_com]) { // 1
if(type[i]) {
ans[i] = 2;
}else {
if(n1 > 0) {
ans[i] = 1;
n1--;
}else {
ans[i] = 3;
}
}
}else { // 0
if(!type[i]) {
ans[i] = 2;
}else {
if(n1 > 0) {
ans[i] = 1;
n1--;
}else {
ans[i] = 3;
}
}
}
}
for(int i = 0; i < n; i++) {
out.print(ans[i]);
}
out.println();
}else {
out.println("NO");
}
}
public static void main(String[] args) {
new Thread(null, null, "Thread", 1 << 27) {
public void run() {
try {
out = new PrintWriter(new BufferedOutputStream(System.out));
s = new FastReader(System.in);
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
public static PrintWriter out;
public static FastReader s;
public static class FastReader {
private InputStream stream;
private byte[] buf = new byte[4096];
private int curChar, snumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException E) {
throw new InputMismatchException();
}
}
if (snumChars <= 0) {
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int number = 0;
do {
number *= 10;
number += c - '0';
c = read();
} while (!isSpaceChar(c));
return number * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
long sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long number = 0;
do {
number *= 10L;
number += (long) (c - '0');
c = read();
} while (!isSpaceChar(c));
return number * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextLong();
}
return arr;
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndofLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndofLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 73453b626f949a636c245ceaed9bcb98 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
//static final long MOD = 998244353L;
//static final long INF = 1000000000000000007L;
static final long MOD = 1000000007L;
static final int INF = 1000000007;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int N = sc.ni();
int M = sc.ni();
int a = sc.ni();
int b = sc.ni();
int c = sc.ni();
ArrayList<Integer>[] graph = new ArrayList[N];
for (int i = 0; i < N; i++) {
graph[i] = new ArrayList<Integer>();
}
for (int i = 0; i < M; i++) {
int n1 = sc.ni()-1;
int n2 = sc.ni()-1;
graph[n1].add(n2);
graph[n2].add(n1);
}
ArrayList<int[]> pairs = new ArrayList<int[]>();
ArrayList<ArrayList<Integer>> whiteNodes = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> blackNodes = new ArrayList<ArrayList<Integer>>();
int[] vis = new int[N]; //0 unvis, 1 white, 2 black (bipartite graph)
for (int i = 0; i < N; i++) {
if (vis[i] != 0) {
continue;
}
vis[i] = 1;
ArrayList<Integer> wNodes = new ArrayList<Integer>();
wNodes.add(i);
ArrayList<Integer> bNodes = new ArrayList<Integer>();
ArrayDeque<Integer> bfs = new ArrayDeque<Integer>();
bfs.add(i);
while (!bfs.isEmpty()) {
int node = bfs.poll();
for (int next: graph[node]) {
if (vis[next] == vis[node]) {
//it is impossible to color this graph
pw.println("NO");
pw.close();
return;
}
if (vis[next] == 0) {
vis[next] = 3-vis[node];
if (vis[next]==1)
wNodes.add(next);
else
bNodes.add(next);
bfs.add(next);
}
}
}
pairs.add(new int[]{wNodes.size(),bNodes.size()});
whiteNodes.add(wNodes);
blackNodes.add(bNodes);
}
boolean[][] dp = new boolean[pairs.size()+1][N+1];
dp[0][0] = true;
for (int i = 1; i <= pairs.size(); i++) {
int[] p = pairs.get(i-1);
for (int j = 0; j <= N; j++) {
if (j-p[0]>=0)
dp[i][j] |= dp[i-1][j-p[0]];
if (j-p[1]>=0)
dp[i][j] |= dp[i-1][j-p[1]];
}
}
if (dp[pairs.size()][b]) {
pw.println("YES");
int[] color = new int[N];
int num = b;
for (int i = pairs.size()-1; i >= 0; i--) {
int[] p = pairs.get(i);
if (num-p[0] >= 0 && dp[i][num-p[0]]) {
for (int n: whiteNodes.get(i))
color[n] = 2;
num -= p[0];
} else if (num-p[1] >= 0 && dp[i][num-p[1]]) {
for (int n: blackNodes.get(i))
color[n] = 2;
num -= p[1];
}
}
StringBuilder ans = new StringBuilder();
for (int i = 0; i < N; i++) {
if (color[i] == 0) {
if (a > 0) {
color[i] = 1;
a--;
} else {
color[i] = 3;
c--;
}
}
ans.append(color[i]);
}
pw.println(ans.toString());
} else {
pw.println("NO");
}
pw.close();
}
public static long dist(long[] p1, long[] p2) {
return (Math.abs(p2[0]-p1[0])+Math.abs(p2[1]-p1[1]));
}
//Find the GCD of two numbers
public static long gcd(long a, long b) {
if (a < b) return gcd(b,a);
if (b == 0)
return a;
else
return gcd(b,a%b);
}
//Fast exponentiation (x^y mod m)
public static long power(long x, long y, long m) {
if (y < 0) return 0L;
long ans = 1;
x %= m;
while (y > 0) {
if(y % 2 == 1)
ans = (ans * x) % m;
y /= 2;
x = (x * x) % m;
}
return ans;
}
public static int[] shuffle(int[] array) {
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
public static long[] shuffle(long[] array) {
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
long temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
public static int[][] shuffle(int[][] array) {
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
public static int[][] sort(int[][] array) {
//Sort an array (immune to quicksort TLE)
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[0]-b[0]; //ascending order
}
});
return array;
}
public static long[][] sort(long[][] array) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
long[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
Arrays.sort(array, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] < b[0])
return -1;
else
return 1;
}
});
return array;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
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 ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 424236b37a63240b7118d860a77a3559 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static class node{
int a, b;
public node(int x, int y){
a = x;
b = y;
}
}
static ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
static ArrayList<node> f = new ArrayList<node>();
static ArrayList<Integer> dfst = new ArrayList<Integer>();
static boolean vis[];
static int clr[], finalcl[];
static int s1, s0;
static int dp[][];
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb = new StringBuffer();
String s[] = (br.readLine()).split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
s = (br.readLine()).split(" ");
int n1 = Integer.parseInt(s[0]);
int n2 = Integer.parseInt(s[1]);
int n3 = Integer.parseInt(s[2]);
for(int i = 0; i <= n; i++){
arr.add(new ArrayList<Integer>());
}
for(int i = 0; i < m; i++){
s = (br.readLine()).split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
arr.get(a).add(b);
arr.get(b).add(a);
}
vis = new boolean[n + 1];
clr = new int[n + 1];
boolean ok = false;
for(int i = 1; i <= n; i++){
if(!vis[i]){
s1 = 0; s0 = 0;
dfst.add(i);
boolean ans = dfs(i, 0);
if(ans) f.add(new node(s0, s1));
else {
ok = true;
break;
}
}
}
dp = new int[dfst.size() + 1][n + 1];
for(int i = 0; i <= dfst.size(); i++){
Arrays.fill(dp[i], -1);
}
finalcl = new int[n + 1];
if(!ok){
dp[0][0] = 0;
for(int i = 0; i < dfst.size(); i++){
for(int j = 0; j < n; j++){
if(dp[i][j] != -1){
node temp = f.get(i);
dp[i + 1][j + temp.a] = 0;
dp[i + 1][j + temp.b] = 1;
}
}
}
if(dp[dfst.size()][n2] != -1){
sb.append("YES\n");
int temp = n2;
for(int i = dfst.size(); i >= 1; i--){
if(dp[i][temp] == 0){
vis = new boolean[n + 1];
dfs2(dfst.get(i - 1), 0, 0);
temp -= f.get(i - 1).a;
}
else{
vis = new boolean[n + 1];
dfs2(dfst.get(i - 1), 1, 0);
temp -= f.get(i - 1).b;
}
}
for(int i = 1; i <= n; i++){
if(finalcl[i] != 2 && n1 > 0) {finalcl[i] = 1; n1--;}
else if(finalcl[i] != 2) finalcl[i] = 3;
sb.append(finalcl[i]);
}
}
else sb.append("NO\n");
}
else{
sb.append("NO\n");
}
System.out.println(sb);
}
public static boolean dfs(int node, int par){
vis[node] = true;
if(clr[par] == 0){ clr[node] = 1; s1++;}
else {clr[node] = 0; s0++;}
for(int i = 0; i < arr.get(node).size(); i++){
int t = arr.get(node).get(i);
if(t != par){
if(!vis[t]){
boolean ans = dfs(t, node);
if(!ans) return false;
}
else{
if(clr[t] == clr[node])
return false;
}
}
}
return true;
}
public static void dfs2(int node, int color, int par){
vis[node] = true;
if(clr[node] == color) finalcl[node] = 2;
for(int i = 0; i < arr.get(node).size(); i++){
int t = arr.get(node).get(i);
if(!vis[t] && t != par) dfs2(t, color, node);
}
}
}
| Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 3f882a77e0ad7dbfd6925157dc674c89 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class E
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
st = new StringTokenizer(infile.readLine());
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
LinkedList<Integer>[] edges = new LinkedList[N+1];
for(int i=1; i <= N; i++)
edges[i] = new LinkedList<Integer>();
for(int i=0; i < M; i++)
{
st = new StringTokenizer(infile.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
edges[a].add(b);
edges[b].add(a);
}
int[] color = new int[N+1];
ArrayList<Integer> heads = new ArrayList<Integer>();
ArrayList<Pair> ls = new ArrayList<Pair>();
for(int i=1; i <= N; i++)
if(color[i] == 0)
{
color[i] = 1;
heads.add(i);
Pair p = new Pair(1, 0);
Queue<Integer> q = new LinkedList<Integer>();
q.add(i);
while(q.size() > 0)
{
int curr = q.poll();
for(int next: edges[curr])
{
if(color[next] == color[curr])
{
System.out.println("NO");
return;
}
if(color[next] == 0)
{
color[next] = 2;
p.even++;
if(color[curr] == 2)
{
color[next]--;
p.even--;
p.odd++;
}
q.add(next);
}
}
}
ls.add(p);
}
int[][] dp = new int[ls.size()][N+1];
for(int i=0; i < ls.size(); i++)
Arrays.fill(dp[i], -1);
dp[0][ls.get(0).odd] = 0;
dp[0][ls.get(0).even] = 0;
for(int t=0; t < ls.size()-1; t++)
for(int w=0; w <= N; w++)
if(dp[t][w] != -1)
{
Pair p = ls.get(t+1);
if(p.odd+w <= N)
dp[t+1][p.odd+w] = w;
if(p.even+w <= N)
dp[t+1][p.even+w] = w;
}
if(dp[ls.size()-1][B] == -1 && dp[ls.size()-1][A+C] == -1)
System.out.println("NO");
else
{
int t = ls.size()-1;
int w = B;
boolean odd = false;
if(dp[t][w] == -1)
{
w = A+C;
//odd = true;
}
int[] res = new int[N+1];
while(t >= 0)
{
int wc = w-dp[t][w];
Queue<Integer> q = new LinkedList<Integer>();
q.add(heads.get(t));
res[heads.get(t)] = 2;
if(ls.get(t).odd != wc)
res[heads.get(t)] = 1;
while(q.size() > 0)
{
int curr = q.poll();
for(int next: edges[curr])
if(res[next] == 0)
{
res[next] = 1;
if(res[curr] == 1)
res[next]++;
q.add(next);
}
}
w = dp[t][w];
t--;
}
int cnt = C;
for(int i=1; i <= N; i++)
if(res[i] == 1 && cnt > 0)
{
res[i] = 3;
cnt--;
}
StringBuilder sb = new StringBuilder("YES\n");
int tc = 0;
for(int i=1; i <= N; i++)
{
if(res[i] == 2)
tc++;
sb.append(res[i]);
}
System.out.println(sb);
}
}
}
class Pair
{
public int odd;
public int even;
public Pair(int a, int b)
{
odd = a;
even = b;
}
public int sum()
{
return odd+even;
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 6b085d279ecfc3340385ff7b13d81dbe | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class E
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
st = new StringTokenizer(infile.readLine());
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
ArrayList<Integer>[] edges = new ArrayList[N+1];
for(int i=1; i <= N; i++)
edges[i] = new ArrayList<Integer>();
for(int i=0; i < M; i++)
{
st = new StringTokenizer(infile.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
edges[a].add(b);
edges[b].add(a);
}
int[] color = new int[N+1];
ArrayList<Integer> heads = new ArrayList<Integer>();
ArrayList<Pair> ls = new ArrayList<Pair>();
for(int i=1; i <= N; i++)
if(color[i] == 0)
{
color[i] = 1;
heads.add(i);
Pair p = new Pair(1, 0);
Queue<Integer> q = new LinkedList<Integer>();
q.add(i);
while(q.size() > 0)
{
int curr = q.poll();
for(int next: edges[curr])
{
if(color[next] == color[curr])
{
System.out.println("NO");
return;
}
if(color[next] == 0)
{
color[next] = 2;
p.even++;
if(color[curr] == 2)
{
color[next]--;
p.even--;
p.odd++;
}
q.add(next);
}
}
}
ls.add(p);
}
int[][] dp = new int[ls.size()][N+1];
for(int i=0; i < ls.size(); i++)
Arrays.fill(dp[i], -1);
dp[0][ls.get(0).odd] = 0;
dp[0][ls.get(0).even] = 0;
for(int t=0; t < ls.size()-1; t++)
for(int w=0; w <= N; w++)
if(dp[t][w] != -1)
{
Pair p = ls.get(t+1);
if(p.odd+w <= N)
dp[t+1][p.odd+w] = w;
if(p.even+w <= N)
dp[t+1][p.even+w] = w;
}
if(dp[ls.size()-1][B] == -1 && dp[ls.size()-1][A+C] == -1)
System.out.println("NO");
else
{
int t = ls.size()-1;
int w = B;
boolean odd = false;
if(dp[t][w] == -1)
{
w = A+C;
//odd = true;
}
int[] res = new int[N+1];
while(t >= 0)
{
int wc = w-dp[t][w];
Queue<Integer> q = new LinkedList<Integer>();
q.add(heads.get(t));
res[heads.get(t)] = 2;
if(ls.get(t).odd != wc)
res[heads.get(t)] = 1;
while(q.size() > 0)
{
int curr = q.poll();
for(int next: edges[curr])
if(res[next] == 0)
{
res[next] = 1;
if(res[curr] == 1)
res[next]++;
q.add(next);
}
}
w = dp[t][w];
t--;
}
int cnt = C;
for(int i=1; i <= N; i++)
if(res[i] == 1 && cnt > 0)
{
res[i] = 3;
cnt--;
}
StringBuilder sb = new StringBuilder("YES\n");
int tc = 0;
for(int i=1; i <= N; i++)
{
if(res[i] == 2)
tc++;
sb.append(res[i]);
}
System.out.println(sb);
}
}
}
class Pair
{
public int odd;
public int even;
public Pair(int a, int b)
{
odd = a;
even = b;
}
public int sum()
{
return odd+even;
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 4340b42eb7b4543bbda4691e4ff17b40 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
static int MOD = 1000000007;
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solve();
m.close();
}
void close() throws IOException {
pw.flush();
pw.close();
br.close();
}
int ri() throws IOException {
return Integer.parseInt(br.readLine());
}
long rl() throws IOException {
return Long.parseLong(br.readLine());
}
int[] ril() throws IOException {
String[] tokens = br.readLine().split(" ");
int[] A = new int[tokens.length];
for (int i = 0; i < A.length; i++)
A[i] = Integer.parseInt(tokens[i]);
return A;
}
long[] rll() throws IOException {
String[] tokens = br.readLine().split(" ");
long[] A = new long[tokens.length];
for (int i = 0; i < A.length; i++)
A[i] = Long.parseLong(tokens[i]);
return A;
}
boolean[] visited;
void solve() throws IOException {
int[] nm = ril();
int n = nm[0];
int m = nm[1];
int[] ni = ril();
int n1 = ni[0];
int n2 = ni[1];
int n3 = ni[2];
List<List<Integer>> adj = new ArrayList<>(n);
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int i = 0; i < m; i++) {
int[] uv = ril();
adj.get(uv[0]-1).add(uv[1]-1);
adj.get(uv[1]-1).add(uv[0]-1);
}
visited = new boolean[n];
List<Set<Integer>> redsList = new ArrayList<>();
List<Set<Integer>> bluesList = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!visited[i]) {
reds = new HashSet<>();
blues = new HashSet<>();
visited[i] = true;
reds.add(i);
int ret = dfs(adj, i, true);
if (ret == -1) {
pw.println("NO");
return;
}
redsList.add(reds);
bluesList.add(blues);
}
}
// dp[i][j] is true if using pairs [0..i] we can have
// sum of j
boolean[][] dp = new boolean[redsList.size()][n+1];
dp[0][redsList.get(0).size()] = dp[0][bluesList.get(0).size()] = true;
for (int i = 1; i < redsList.size(); i++) {
int numR = redsList.get(i).size();
int numB = bluesList.get(i).size();
for (int j = 0; j <= n2; j++) {
if (j-numR >= 0 && dp[i-1][j-numR]) {
dp[i][j] = true;
continue;
}
if (j-numB >= 0 && dp[i-1][j-numB]) {
dp[i][j] = true;
continue;
}
}
}
if (!dp[redsList.size()-1][n2]) {
pw.println("NO");
return;
}
pw.println("YES");
int[] color = new int[n];
int j = n2;
for (int i = redsList.size() - 1; i > 0; i--) {
int numR = redsList.get(i).size();
int numB = bluesList.get(i).size();
if (j-numR >= 0 && dp[i-1][j-numR]) {
for (int x : redsList.get(i)) color[x] = 2;
j -= numR;
} else {
for (int x : bluesList.get(i)) color[x] = 2;
j -= numB;
}
}
if (j == redsList.get(0).size()) {
for (int x : redsList.get(0)) color[x] = 2;
} else {
for (int x : bluesList.get(0)) color[x] = 2;
}
for (int i = 0; i < color.length; i++) {
if (color[i] == 2) continue;
if (n1 > 0) {
color[i] = 1;
n1--;
} else {
color[i] = 3;
n3--;
}
}
for (int c : color) pw.print(c);
pw.println();
}
Set<Integer> reds;
Set<Integer> blues;
int dfs(List<List<Integer>> adj, int u, boolean red) {
for (int v : adj.get(u)) {
if (!visited[v]) {
visited[v] = true;
if (red) blues.add(v);
else reds.add(v);
dfs(adj, v, !red);
} else {
if (reds.contains(v) && red || blues.contains(v) && !red) return -1;
}
}
return 0;
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | a896aad4a72faeff60115b4b2d548755 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
Reader rd = new Reader();
int n = rd.nextInt(), m = rd.nextInt();
int n1 = rd.nextInt(), n2 = rd.nextInt(), n3 = rd.nextInt();
HashSet<Integer>[] edges = new HashSet[n + 1];
for(int i = 1; i <= n; i++) edges[i] = new HashSet<>();
for(int i = 0; i < m; i++) {
int a = rd.nextInt(), b = rd.nextInt();
edges[a].add(b);
edges[b].add(a);
}
int[] display = new int[n + 1];
int[] display2 = new int[n + 1];
int[] ds = new int[n + 1];
int p = 1;
for(int i = 1; i <= n; i++) {
if(ds[i] == 0) {
Queue<Integer> que = new LinkedList<>();
que.add(i);
ds[i] = p;
if(ds[i] > 0) display[p]++;
while(!que.isEmpty()) {
int loc = que.poll();
for(int next : edges[loc]) {
if(ds[next] == ds[loc]) {System.out.println("NO"); return;}
if(ds[next] != 0) continue;
que.add(next);
ds[next] = -ds[loc];
if(ds[next] > 0) display[p]++;
else display2[p]++;
}
}
p++;
}
}
p -= 1;
boolean[][] dp = new boolean[p + 1][n2 + 1];
boolean[][] pre = new boolean[p + 1][n2 + 1];
for(boolean[] arr : dp) Arrays.fill(arr, false);
dp[0][0] = true;
for(int i = 1; i <= p; i++) {
for(int j = 0; j <= n2; j++) {
if(j - display[i] >= 0 && dp[i - 1][j - display[i]]) {dp[i][j] = true; pre[i][j] = true;}
else if(j - display2[i] >= 0 && dp[i - 1][j - display2[i]]) {dp[i][j] = true; pre[i][j] = false;}
}
}
if(!dp[p][n2]){System.out.println("NO"); return;}
HashMap<Integer, Integer> map = new HashMap<>();
while(p > 0) {
if(pre[p][n2]) {
map.put(p, 2);
map.put(-p, 1);
n2 -= display[p];
} else {
map.put(p, 1);
map.put(-p, 2);
n2 -= display2[p];
}
p--;
}
System.out.println("YES");
for(int loc : ds) {
if(map.get(loc) == null) continue;
int val = map.get(loc);
if(map.get(loc) == 2) System.out.print(2);
else {
if(n1 > 0) {
System.out.print(1);
n1--;
} else {
System.out.print(3);
}
}
}
}
//Fast IO class
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 | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | f177d416d0a9d00dd48103859d8a1aaa | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 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(){
work();
out.flush();
}
long mod=998244353L;
int[][] dir=new int[][] {{0,1},{1,0},{0,-1},{-1,0}};
long inf=Long.MAX_VALUE;
long gcd(long a,long b) {
return a==0?b:gcd(b%a,a);
}
ArrayList<Integer>[] graph;
int[] color;
void work() {
int n=ni(),m=ni();
int a1=ni(),a2=ni(),a3=ni();
graph=ng(n,m);
color=new int[n];
ArrayList<ArrayList<Integer>[]> list=new ArrayList<>();
for(int i=0;i<n;i++) {
if(color[i]==0) {
ArrayList<Integer>[] ls=(ArrayList<Integer>[])new ArrayList[2];
ls[0]=new ArrayList<>();
ls[1]=new ArrayList<>();
if(!dfs(i,1,ls)) {
out.println("NO");
return;
}
list.add(ls);
}
}
int[][] dp=new int[list.size()][n+1];
int size=list.size();
dp[0][list.get(0)[0].size()]=1;
dp[0][list.get(0)[1].size()]=2;
for(int i=0;i<list.size()-1;i++) {
for(int j=0;j<=a2;j++) {
if(dp[i][j]>0){
int s1=list.get(i+1)[0].size();
int s2=list.get(i+1)[1].size();
dp[i+1][j+s1]=1;
dp[i+1][j+s2]=2;
}
}
}
if(dp[size-1][a2]==0) {
out.println("NO");
return;
}
int cur=a2;
Arrays.fill(color, 1);
for(int i=size-1;i>=0;i--) {
int idx=dp[i][cur]-1;
ArrayList<Integer> l=list.get(i)[idx];
for(int k:l) {
color[k]=2;
}
cur-=l.size();
}
for(int i=0,j=0;j<a3;i++) {
if(color[i]==1) {
color[i]=3;
j++;
}
}
out.println("YES");
for(int c:color) {
out.print(c);
}
}
private boolean dfs(int node,int col,ArrayList<Integer>[] ls) {
color[node]=col;
int next=col==1?2:1;
ls[col-1].add(node);
for(int nn:graph[node]) {
if(color[nn]==0&&!dfs(nn,next,ls)) {
return false;
}else if(color[nn]!=next) {
return false;
}
}
return true;
}
//input
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,i});
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 | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | b09b19a9bef26c001aaed7c20ffbd3b9 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
public static void main(String[] args) throws Exception {
new template().run();
}
boolean[] b, vis;
ArrayList<Integer>[] adj;
ArrayList<Integer>[][] comp;
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = f.nextInt(), m = f.nextInt();
b = new boolean[n];
vis = new boolean[n];
adj = new ArrayList[n];
comp = new ArrayList[n][2];
for(int i = 0; i < n; i++)
adj[i] = new ArrayList<>();
int n1 = f.nextInt(), n2 = f.nextInt(), n3 = f.nextInt();
for(int i = 0; i < m; i++) {
int a= f.nextInt()-1, b = f.nextInt()-1;
adj[a].add(b);
adj[b].add(a);
}
int cn = 0;
boolean ans = true;
for(int i = 0; i < n; i++) {
if(!vis[i]) {
comp[cn][0] = new ArrayList<>();
comp[cn][1] = new ArrayList<>();
ans &= dfs(i,cn++, true);
}
}
if(ans) {
boolean[][] use = new boolean[cn+1][n2+1];
boolean[][] pos = new boolean[cn+1][n2+1];
pos[0][0] = true;
for(int i = 0; i < cn; i++)
for(int j = 0; j <= n2; j++)
if(pos[i][j]) {
if(j+comp[i][0].size() <= n2) {
pos[i+1][j+comp[i][0].size()] = true;
use[i+1][j+comp[i][0].size()] = false;
}
if(j+comp[i][1].size() <= n2) {
pos[i+1][j+comp[i][1].size()] = true;
use[i+1][j+comp[i][1].size()] = true;
}
}
if(pos[cn][n2]) {
out.println("YES");
int[] res = new int[n];
for(int i = cn; i > 0; i--) {
if(use[i][n2]) {
for(int j : comp[i-1][1])
res[j] = 2;
n2 -= comp[i-1][1].size();
} else {
for(int j : comp[i-1][0])
res[j] = 2;
n2 -= comp[i-1][0].size();
}
}
for(int i = 0; i < res.length; i++)
if(res[i] == 0)
if(n1-- <= 0) res[i] = 3;
else res[i] = 1;
for(int i : res) out.print(i);
out.println();
} else out.println("NO");
} else out.println("NO");
out.flush();
}
public boolean dfs(int i, int cn, boolean val) {
if(vis[i]) return val == b[i];
vis[i] = true;
b[i] = val;
if(val) comp[cn][0].add(i);
else comp[cn][1].add(i);
boolean ret = true;
for(int j : adj[i])
ret &= dfs(j,cn,val^true);
return ret;
}
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 | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 019251df17543fd33fd82fc1148ee28d | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.BufferedOutputStream;
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.List;
import java.util.StringTokenizer;
public class E {
//--------------------------------------------------------
private static final MyScanner in = new MyScanner(System.in);
private static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws Exception {
Solver solver = new Solver();
solver.solve();
out.close();
}
private static class Solver {
private void solve() throws Exception {
int n = in.nextInt();
int m = in.nextInt();
int n1 = in.nextInt();
int n2 = in.nextInt();
int n3 = in.nextInt();
List<List<Integer>> edge = new ArrayList<>(n + 1);
for (int i = 0; i <= n; i++) {
edge.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
edge.get(a).add(b);
edge.get(b).add(a);
}
int[] flag = new int[n + 1];
Arrays.fill(flag, -1);
List<List<List<Integer>>> allBG = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (flag[i] >= 0) {
continue;
}
List<List<Integer>> bg = new ArrayList<>(Arrays.asList(new ArrayList<>(), new ArrayList<>()));
flag[i] = 0;
bg.get(flag[i]).add(i);
if (!dfs(flag, i, edge, bg)) {
out.println("NO");
return;
}
allBG.add(bg);
}
int[][] d = new int[allBG.size() + 1][n + 1];
for (int[] ints : d) {
Arrays.fill(ints, -1);
}
d[0][0] = 0;
for (int i = 1; i <= allBG.size(); i++) {
for (int j = 0; j <= n; j++) {
if (d[i - 1][j] >= 0) {
d[i][j + allBG.get(i-1).get(0).size()] = 0;
d[i][j + allBG.get(i-1).get(1).size()] = 1;
}
}
}
if (d[allBG.size()][n2] < 0) {
out.println("NO");
return;
}
int[] ans = new int[n+1];
int i = allBG.size();
while (i > 0) {
List<List<Integer>> bg = allBG.get(i - 1);
List<Integer> part2 = bg.get(d[i][n2]);
List<Integer> part13 = bg.get(1-d[i][n2]);
for (Integer v: part2) {
ans[v] = 2;
}
for (Integer v : part13) {
if (n1 > 0) {
ans[v] = 1;
n1--;
} else {
ans[v] = 3;
n3--;
}
}
n2 -= part2.size();
i--;
}
out.println("YES");
for (int k = 1; k <= n; k++) {
out.print(ans[k]);
}
out.println();
}
private boolean dfs(int[] flag, int node, List<List<Integer>> edges,
List<List<Integer>> bg) {
List<Integer> next = edges.get(node);
for (Integer nn : next) {
if (flag[nn] < 0) {
flag[nn] = 1 - flag[node];
bg.get(flag[nn]).add(nn);
if (!dfs(flag, nn, edges, bg)) {
return false;
}
} else {
if (flag[nn] == flag[node]) {
return false;
}
}
}
return true;
}
}
public static class MyScanner {
private final BufferedReader br;
private StringTokenizer st;
public MyScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
} | Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | c3ecf0bc725f0e003176fd7846599ce1 | train_001.jsonl | 1589707200 | You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertex $$$x$$$. If there are multiple valid labelings, print any of them. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.IntStream;
import java.util.InputMismatchException;
import java.util.HashMap;
import java.util.OptionalInt;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.Collection;
import java.util.Set;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.Objects;
import java.util.List;
import java.util.stream.Stream;
import java.io.Writer;
import java.util.Optional;
import java.util.Queue;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author out_of_the_box
*/
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);
EGraphColoring solver = new EGraphColoring();
solver.solve(1, in, out);
out.close();
}
static class EGraphColoring {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int no = in.nextInt();
int nt = in.nextInt();
int nh = in.nextInt();
Set<Integer> zrs = new HashSet<>();
Graph<Integer, Graph.BaseEdge<Integer>> g = new AdjacencyList<>();
for (int i = 0; i < n; i++) {
g.addVertex(i);
zrs.add(i);
}
for (int i = 0; i < m; i++) {
int u = in.nextInt();
u--;
int v = in.nextInt();
v--;
zrs.remove(u);
zrs.remove(v);
Graph.BaseEdge<Integer> edge = Graph.BaseEdge.of(u, v);
g.addEdge(edge);
}
int[] assign = new int[n];
boolean[] done = new boolean[n];
int[] temp = new int[n];
boolean[] disc = new boolean[n];
int tc = 0;
List<Pair<Set<Integer>, Set<Integer>>> sets = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!done[i]) {
Queue<Integer> queue = new LinkedList<>();
queue.add(i);
disc[i] = true;
temp[i] = 1;
done[i] = true;
List<Set<Integer>> setlist = new ArrayList<>();
setlist.add(new HashSet<>());
setlist.add(new HashSet<>());
setlist.get(0).add(i);
while (!queue.isEmpty()) {
int tp = queue.poll();
done[tp] = true;
List<Graph.BaseEdge<Integer>> edges = g.getEdges(tp);
int val = temp[tp];
for (Graph.BaseEdge<Integer> edge : edges) {
int v = edge.second;
if (temp[v] == val) {
out.println("NO");
return;
}
temp[v] = getOtherLabel(val);
int ind = temp[v] - 1;
setlist.get(ind).add(v);
if (!disc[v]) {
disc[v] = true;
queue.add(v);
}
}
}
int minLabel = (setlist.get(0).size() <= setlist.get(1).size()) ? (1) : 2;
for (int num : setlist.get(minLabel - 1)) {
assign[num] = 2;
tc++;
}
int othl = getOtherLabel(minLabel);
for (int num : setlist.get(othl - 1)) {
assign[num] = 4;
}
sets.add(Pair.of(setlist.get(minLabel - 1), setlist.get(othl - 1)));
}
}
if (tc > nt) {
out.println("NO");
return;
}
int diff = nt - tc;
if (diff != 0) {
List<Integer> diffs = sets.stream().map(pr -> pr.getRight().size() - pr.getLeft().size())
.collect(Collectors.toList());
Optional<List<Integer>> choices = subsetSum(diff, diffs);
if (!choices.isPresent()) {
out.println("NO");
return;
}
List<Integer> choiceList = choices.orElseThrow(() -> new RuntimeException("Cannot happen"));
for (int choice : choiceList) {
Set<Integer> my = sets.get(choice).getLeft();
for (int mys : my) {
assign[mys] = 4;
}
Set<Integer> theirs = sets.get(choice).getRight();
for (int their : theirs) {
assign[their] = 2;
}
}
}
// if (diff > zrs.size()) {
// out.println("NO");
// return;
// }
// for (int zr : zrs) {
// if (diff == 0) break;
// assertion(assign[zr] != 2,
// String.format("assign[zr] != 2. zr = %d, assign[zr] = %d", zr, assign[zr]));
// assign[zr] = 2;
// diff--;
// }
//
List<Integer> ohs = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (assign[i] == 4) {
ohs.add(i);
} else if (assign[i] == 0) {
MiscUtility.assertion(false, String.format("Assign[%d] = 0", i));
}
}
int tot = no + nh;
MiscUtility.assertion(ohs.size() == tot, String.format("ohs.size [%d] not equal to tot [%d]", ohs.size(), tot));
for (int i = 0; i < no; i++) {
assign[ohs.get(i)] = 1;
}
for (int i = no; i < tot; i++) {
assign[ohs.get(i)] = 3;
}
out.println("YES");
for (int i = 0; i < n; i++) {
out.print(assign[i]);
}
out.println();
}
private Optional<List<Integer>> subsetSum(int val, List<Integer> arr) {
int len = arr.size();
int maxVal = Math.max(val, arr.stream().mapToInt(i -> i).max()
.orElseThrow(() -> new RuntimeException("Empty components array")));
boolean[][] dp = new boolean[len][maxVal + 1];
boolean[][] choice = new boolean[len][maxVal + 1];
dp[0][0] = true;
dp[0][arr.get(0)] = true;
choice[0][arr.get(0)] = true;
for (int i = 1; i < len; i++) {
for (int j = 0; j <= val; j++) {
if (dp[i - 1][j]) {
dp[i][j] = true;
} else if (j >= arr.get(i) && dp[i - 1][j - arr.get(i)]) {
dp[i][j] = true;
choice[i][j] = true;
}
}
}
if (!dp[len - 1][val]) {
return Optional.empty();
} else {
List<Integer> ret = new ArrayList<>();
int vind = val;
for (int i = len - 1; i >= 0; i--) {
MiscUtility.assertion(dp[i][vind], String.format("Subset sum issue: dp[%d][%d] is false.", i, vind));
if (choice[i][vind]) {
ret.add(i);
vind -= arr.get(i);
}
}
return Optional.of(ret);
}
}
private int getOtherLabel(int label) {
if (label == 1) return 2;
return 1;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
static class AdjacencyList<V, E extends Graph.Edge<V, E>> implements Graph<V, E> {
public Map<V, List<E>> adjList;
private Map<E, E> reverseMap;
public boolean directed;
public AdjacencyList() {
this.adjList = new HashMap<>();
this.directed = false;
this.reverseMap = new HashMap<>();
}
public AdjacencyList(boolean directed) {
this.adjList = new HashMap<>();
this.directed = directed;
this.reverseMap = new HashMap<>();
}
public List<E> getEdges(V vertex) {
return Optional.ofNullable(adjList.get(vertex)).orElseGet(ArrayList::new);
}
public Graph<V, E> addVertex(V v) {
List<E> edges = Optional.ofNullable(adjList.get(v)).orElseGet(ArrayList::new);
adjList.put(v, edges);
return this;
}
public Graph<V, E> addEdge(E e) {
V v1 = e.first;
V v2 = e.second;
List<E> edges1 = Optional.ofNullable(adjList.get(v1)).orElseGet(ArrayList::new);
edges1.add(e);
adjList.put(v1, edges1);
if (!directed) {
E reverseEdge = e.reverse();
List<E> edges2 = Optional.ofNullable(adjList.get(v2)).orElseGet(ArrayList::new);
edges2.add(reverseEdge);
adjList.put(v2, edges2);
reverseMap.put(e, reverseEdge);
reverseMap.put(reverseEdge, e);
}
return this;
}
}
static class MiscUtility {
public static void assertion(boolean condition, String message) {
if (!condition) {
throw new RuntimeException("Assertion failed. " + message);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface Graph<V, E extends Graph.Edge<V, E>> {
Graph<V, E> addVertex(V v);
Graph<V, E> addEdge(E e);
List<E> getEdges(V vertex);
abstract class Edge<V, E extends Graph.Edge<V, E>> {
public V first;
public V second;
public Edge(V first, V second) {
this.first = first;
this.second = second;
}
public abstract E reverse();
}
class BaseEdge<V> extends Graph.Edge<V, Graph.BaseEdge<V>> {
private BaseEdge(V first, V second) {
super(first, second);
}
public static <A> Graph.BaseEdge<A> of(A fir, A sec) {
return new Graph.BaseEdge<>(fir, sec);
}
public Graph.BaseEdge<V> reverse() {
return Graph.BaseEdge.of(second, first);
}
}
}
static class Pair<L, R> {
private L left;
private R right;
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() {
return left;
}
public R getRight() {
return right;
}
public static <A, B> Pair<A, B> of(A a, B b) {
return new Pair<>(a, b);
}
public String toString() {
return "Pair{" +
"left=" + left +
", right=" + right +
'}';
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(left, pair.left) &&
Objects.equals(right, pair.right);
}
public int hashCode() {
return Objects.hash(left, right);
}
}
}
| Java | ["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 2 seconds | ["YES\n112323", "NO"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"graphs"
] | 52c634955e1d78971d94098ba1c667d9 | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. | 2,100 | If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes). | standard output | |
PASSED | 8b82fd92d5ada70daa401aeeeb61986a | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes |
import java.io.*;
import java.util.*;
public class B
{
public static void main(String[] args)throws IOException
{
FastReader f=new FastReader();
StringBuffer sb = new StringBuffer();
int test=f.nextInt();
while(test-->0)
{
int n=f.nextInt();
int count=0,ans=0;
int odd=0,b=0;
for(int i=0;i<n;i++)
{
int z=0,o=0;
String s=f.next();
if(s.length()%2!=0)
{
odd++;
ans++;
continue;
}
for(int j=0;j<s.length();j++)
if(s.charAt(j)=='0') z++;
else o++;
if(o%2==0 && z%2==0)
ans++;
else
b++;
}
// System.out.println("ans ini = "+ans);
// System.out.println("b = "+b);
ans+=(b-b%2);
b=b%2;
if(b>0 && odd>0)
ans++;
sb.append(ans+"\n");
}
System.out.println(sb);
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 83f04d769614fbd5ba2451687ff9662d | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | /**
* ******* Created on 6/11/19 4:55 AM*******
*/
import java.io.*;
import java.util.*;
public class B1251 implements Runnable {
class Pair{
int a, b,c;
public Pair(int a ,int b){
this.a= a;
this.b =b;
this.c = Math.abs(a-b);
}
}
private void solve() throws IOException {
int t = reader.nextInt();
while(t-->0){
int q = reader.nextInt();
int odd =0, even=0;
for(int i=0;i<q;i++){
String s = reader.next();
if(s.length()%2 ==1)odd++;
int count =0;
for(int j=0;j<s.length();j++)
if(s.charAt(j)=='0')
count++;
if(count%2 ==1 && s.length()%2==0)even++;
}
writer.println(q- ((odd ==0 && even%2==1)?1 :0 ) );
}
}
public static void main(String[] args) throws IOException {
try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
new B1251().run();
}
}
StandardInput reader;
PrintWriter writer;
@Override
public void run() {
try {
reader = new StandardInput();
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
interface Input extends Closeable {
String next() throws IOException;
default int nextInt() throws IOException {
return Integer.parseInt(next());
}
default long nextLong() throws IOException {
return Long.parseLong(next());
}
default double nextDouble() throws IOException {
return Double.parseDouble(next());
}
default int[] readIntArray() throws IOException {
return readIntArray(nextInt());
}
default int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextInt();
}
return array;
}
default long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextLong();
}
return array;
}
}
private static class StandardInput implements Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer stringTokenizer;
@Override
public void close() throws IOException {
reader.close();
}
@Override
public String next() throws IOException {
if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 1086e1d8b7e1b9cdb4dfc2a475f7155e | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputReader scan = new InputReader();
StringBuilder res = new StringBuilder();
int t = scan.nextInt();
while (t-- > 0) {
int n = scan.nextInt();
int[] ar = new int[n];
int one = 0;
int zero = 0;
int count = 0;
for (int i = 0; i < n; i++) {
String s = scan.next();
if ((s.length() & 1) == 1) {
count++;
}
ar[i] = s.length();
for (char j : s.toCharArray()) {
if (j == '0') {
zero++;
} else {
one++;
}
}
}
if (count == 0 && (one & 1) == 1 && (zero & 1) == 1) {
res.append((n - 1) + "\n");
} else {
res.append(n + "\n");
}
}
System.out.println(res);
}
static class InputReader {
InputStream is = System.in;
byte[] inbuf = new byte[1 << 25];
int lenbuf = 0, ptrbuf = 0;
public InputReader() throws IOException {
lenbuf = is.read(inbuf);
}
public int readByte() {
if (ptrbuf >= lenbuf) {
return -1;
}
return inbuf[ptrbuf++];
}
public boolean hasNext() {
int t = skip();
if (t == -1) {
return false;
}
ptrbuf--;
return true;
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char nextChar() {
return (char) skip();
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public 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);
}
public char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) {
map[i] = ns(m);
}
return map;
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 5e416e77203865c5866efbcae4670df4 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by himanshubhardwaj on 24/10/19.
*/
public class B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 % 2 - o2 % 2;
}
};
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
Integer[] charfreq = new Integer[2];
charfreq[0] = 0;
charfreq[1] = 0;
int a = 0;
int b = 0;
Integer[] size = new Integer[n];
int oddCount = 0;
for (int i = 0; i < n; i++) {
String str = br.readLine();
for (char c : str.toCharArray()) {
charfreq[c - '0']++;
}
if ((str.length() % 2) == 0) {
a++;
} else {
b++;
oddCount++;
}
}
charfreq[0] = charfreq[0] % 2;
charfreq[1] = charfreq[1] % 2;
a = a % 2;
b = b % 2;
if (charfreq[0] == 0) {
if (charfreq[1] == 0) {
pw.append(n + "\n");
} else {
if (b % 2 == 1) {
pw.append(n + "\n");
} else {
pw.append((n - 1) + "\n");
}
}
} else {
if (charfreq[1] == 0) {
if (b % 2 == 1) {
pw.append(n + "\n");
} else {
pw.append((n - 1) + "\n");
}
} else {
if (oddCount == 1) {
pw.append((n - 1) + "\n");
} else if (oddCount == 0) {
pw.append((n - 1) + "\n");
} else {
charfreq[0] = 0;
charfreq[1] = 0;
pw.append(n + "\n");
}
}
}
}
pw.flush();
pw.close();
}
private static String maximumPalindrome(Integer[] charfreq, Integer[] size) {
for (int x : size) {
System.out.print(x + " ");
}
System.out.println();
int count = 0;
for (int i = 0; i < size.length; i++) {
Arrays.sort(charfreq, Collections.reverseOrder());
if (size[i] <= charfreq[0]) {
charfreq[0] -= size[i];
count++;
} else if (size[i] <= charfreq[1]) {
charfreq[1] -= size[i];
count++;
} else {
if ((((charfreq[0] % 2) + (charfreq[1] % 2))) == (size[i] % 2)) {
count++;
}
}
}
return count + "\n";
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 4be47a4afb2edb532383cec569047898 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.math.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
for(int t=sc.nextInt();t>0;t--) {
int n=sc.nextInt();
int one=0,zero=0;
int ji=0,ou=0;
for(int i=0;i<n;i++) {
String str=sc.next();
int a=str.length();
if(a%2==0)ou++;
else ji++;
for(int j=0;j<a;j++) {
if(str.charAt(j)=='1')one++;
else zero++;
}
}
if(ou==n&&zero%2==1)System.out.println(n-1);
else System.out.println(n);
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 88f07d14e7694991d442c32aeff2359e | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int N = in.nextInt();
int numOnes = 0, numZeros = 0;
int lengths[] = new int[N];
for (int i = 0; i < N; i++) {
String s = in.next();
lengths[i] = s.length();
for (int j = s.length() - 1; j >= 0; j--) {
if (s.charAt(j) == '0') {
numZeros++;
} else {
numOnes++;
}
}
}
int ans = 0;
for (int i = 0; i < N; i++) {
while (lengths[i] >= 2 && numOnes >= 2) {
lengths[i] -= 2;
numOnes -= 2;
}
while (lengths[i] >= 2 && numZeros >= 2) {
lengths[i] -= 2;
numZeros -= 2;
}
}
for (int i = 0; i < N; i++) {
if (lengths[i] == 2) {
ans++;
}
}
out.printLine(N - ans);
}
}
static class OutputWriter {
PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tokenizer = null;
public InputReader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (IOException e) {
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | d7bb846f4341c30bc71f720c0296358f | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
for(int jk=0;jk<n;jk++){
int m=in.nextInt();
int put=0;
int flag=0;
for(int i=0;i<m;i++){
String ss=in.next();
int num0=0;int num1=0;
for(int j=0;j<ss.length();j++){
if(ss.charAt(j)=='0') num0++;
else num1++;
}
if(ss.length()%2==1){
flag++;
}
if(ss.length()%2==0){
if(num0%2!=0)
put++;
}
}
if(put%2==0||flag!=0){
System.out.println(m);
}else{
System.out.println(m-1);
}
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 2ad0cd7fffb7e349083e5b9ddd098367 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
public class test {
public static void main(String[] args){
Scanner in1 = new Scanner(System.in);
int Q = in1.nextInt();
while (Q != 0) {
Q--;
int n = in1.nextInt();
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
String st = in1.next();
if (st.length() % 2 == 1) {
x = 1;
continue;
}
for (int j = 0; j < st.length(); j++) {
if (st.charAt(j) == '0') y++;
}
}
if (x == 0 && (y %2 == 1))
System.out.println(n - 1);
else
System.out.println(n);
}
in1.close();
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 57e63a5bd13702d045b8a7b0efe33267 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int Q,n;
int odd =0;
int imperfect =0;
Scanner sc = new Scanner(System.in);
Q = sc.nextInt();
for(int i =0;i<Q;i++){
imperfect =0;odd =0;
n = sc.nextInt();
String str[] = new String[n];
for(int j =0;j<n;j++){
str[j] = sc.next();
if((str[j].length()%2)!=0)
odd++;
else{
int zeros =0;
int ones =0;
for(int k=0;k<str[j].length();k++){
if(str[j].charAt(k)=='1')
ones++;
else
zeros++;
}
if(ones%2!=0)
imperfect++;
}
}
if(odd!=0)
System.out.println(n);
else if(imperfect%2==0)
System.out.println(n);
else
System.out.println(n-1);
}
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 8ca057e3b51fda9ae7c7a05046da2465 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class BinaryPalindromes {
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
private static void solve() {
int n = sc.nextInt();
int even = 0, odd = 0;
for(int i = 0; i < n; i++){
int cnt1 = 0;
String s = sc.next();
for(char ch: s.toCharArray()){
if(ch == '1')
cnt1 += 1;
}
int len = s.length();
if(isEvenInt(len)){
if(isOddInt(cnt1)){
even += 1;
}
} else if(isOddInt(len)) {
odd += 1;
}
}
int ans = n;
if(even!=0 && isOddInt(even) && odd==0)
ans -= 1;
pw.println(ans);
}
public static void main(String args[]) {
try {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
int q = 1;
q = sc.nextInt();
while (q-- > 0) {
solve();
}
}
});
t.start();
t.join();
pw.flush();
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isOddInt(int val) {
return ((val & 1) == 1);
}
public static boolean isEvenInt(int val) {
return ((val & 1) == 0);
}
public static boolean isOddLong(long val) {
return ((val & 1) == 1);
}
public static boolean isEvenLong(long val) {
return ((val & 1) == 0);
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | a18df5705d3c5f2b6123838eacab7d3d | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Integer.min;
public class Solution {
public static void main(String[] args) throws IOException {
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
Scanner sc = new Scanner( System.in );
int t = sc.nextInt();
for ( int z = 0; z < t; z++ ) {
int n = sc.nextInt();
int odd = 0;
int mismatch = 0;
for ( int x = 0; x < n; x++ ) {
String s = sc.next();
int l = s.length();
if ( l%2==1 ) odd++;
for ( int i = 0; i < l/2; i++ ) {
if ( s.charAt( i )!=s.charAt( l-i-1 ) ) {
mismatch++;
}
}
}
mismatch = mismatch%2;
if ( odd>0 ) mismatch = 0;
System.out.println(n-mismatch);
}
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | eadd21ec07fc73d73746859e8286c546 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class BinaryPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int tt=0;tt<t;tt++)
{
int n = sc.nextInt();
int zero = 0;
int count=0;
String[] ar = new String[n];
for (int i = 0; i < n; i++) {
ar[i] = sc.next();
if(ar[i].length()%2==1)
count++;
for(int ii=0;ii<ar[i].length();ii++)
{
String val=ar[i].charAt(ii) + "";
if (val.equals("0")){
zero++;
}
}
}
if(count>0)
System.out.println(n);
else if(zero%2==0)
System.out.println(n);
else
System.out.println(n-1);
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 6eab6e16d7f9f2286633b7673ce8885e | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
public class test {
public static void main(String[] args){
Scanner in1 = new Scanner(System.in);
int Q = in1.nextInt();
while (Q != 0) {
Q--;
int n = in1.nextInt();
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
String st = in1.next();
if (st.length() % 2 == 1) {
x = 1;
continue;
}
for (int j = 0; j < st.length(); j++) {
if (st.charAt(j) == '0') y++;
}
}
if (x == 0 && (y %2 == 1))
System.out.println(n - 1);
else
System.out.println(n);
}
in1.close();
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 84c9e0908423e5a9968921e9f9ba3e76 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.*;
import java.io.*;
public class BinaryPalindromes {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out,false);
int q = scanner.nextInt();
while(q-->0) {
int n = scanner.nextInt();
int odd = 0, bad = 0;
for(int i = 0; i < n; i++) {
String s = scanner.next();
if (s.length() % 2 == 1) odd++;
else {
int ones = 0;
for(char cc: s.toCharArray()) {
if (cc == '1') ones++;
}
if (ones %2 == 1) bad++;
}
}
if (bad %2 == 1 && odd == 0) out.println(n-1);
else out.println(n);
}
out.flush();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 9d24f28f9429ccd200c64b34811fc03b | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static PrintWriter pw;
static HashMap<Character, HashSet<Character>> adj;
static StringBuilder sb;
static boolean[] visit;
static void dfs(char c) {
visit[(int)c-(int)'a']=true;
sb.append(c);
for(char x: adj.get(c)){
if(!visit[(int)x-((int)'a')])
dfs(x);
}
}
public static long gcf(long x, long y) {
while(x%y!=0 && y%x!=0) {
if(x>y)
x%=y;
else
y%=x;
}
return x>y? y:x;
}
static int ceildiv(int x, int y){
return x%y==0? x/y: x/y+1;
}
static int prime(int x, int k) {
int y = (int) Math.sqrt(x);
int ans = 0;
for (int i = 1; i <= y && i <= k; i++) {
if (x % i == 0) {
if (x / i <= k)
return i;
else
ans = i;
}
}
return x / ans;
}
static double tb(int x, int h, int c){
boolean b=true;
long sum=1l*(x/2+1)*(h)+1l*(x/2)*c;
return sum*1.0/x;
}
static long max;
static void dp(int[] arr, int idx){
if(idx==0){
dp1(arr, 0);
return;
}
long sum=0l;
for(int i=idx; i<arr.length; i++){
if(sum>=0)
visit[i]=true;
sum+=arr[i];
max=Math.max(sum, max);
}
}
static void dp1(int[] arr, int idx){
long sum=0l;
visit[0]=true;
for(int i=0; i<arr.length-1; i++){
if(sum>=Math.max(0, arr[arr.length-1]))
visit[i]=true;
sum+=arr[i];
max=Math.max(sum, max);
}
}
static int sum(String s){
int sum=0;
for(int i=0; i<s.length(); i++)
sum+=(int)s.charAt(i)-(int)'0';
return sum;
}
static long pow(long a, long pow){
long ans=1;
while(pow>0){
if((pow&1)==1)
ans*=a;
a*=a;
pow>>=1;
}
return ans;
}
static ArrayList<Character>[] arr;
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner(System.in);
pw = new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int odd=0, one=0, zero=0;
for(int i=0; i<n; i++){
String s=sc.nextLine();
int x=s.length();
odd+=x%2;
for(int j=0; j<x; j++){
if(s.charAt(j)=='1')
one++;
else
zero++;
}
}
pw.println(odd>0 || (one%2==0 && zero%2==0)? n: n-1);
}
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 {
return Double.parseDouble(next());
}
public int[] nextArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public Integer[] nextsort(int n) throws IOException{
Integer[] arr=new Integer[n];
for(int i=0; i<n; i++)
arr[i]=nextInt();
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x, int y) {
this.x=x;
this.y=y;
}
public int hashCode() {
return this.x*1000+this.y;
}
public int compareTo(Pair other) {
if(this.y!=other.y){
return other.y-this.y;
}else{
return (this.x-other.x);
}
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Pair p = (Pair) obj;
return this.x == p.x;
}
public boolean equal(Pair p){
return this.x==p.x && this.y==p.y;
}
}
static class tuple implements Comparable<tuple>{
int x;int y;int z;
public tuple(int x, int y, int z){
this.x=x;
this.y=y;
this.z=z;
}
public int compareTo(tuple other) {
if(this.x!=other.x)
return this.x-other.x;
else {
if(this.y!=other.y)
return this.y-other.y;
else
return this.z-other.z;
}
}
public boolean equal(tuple t){
return this.x==t.x && this.y==t.y;
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | f2f86284a62fb49af9cd3d4b183b9a95 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution implements Runnable
{
static class InputReader
{
private InputStream stream;private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream){this.stream = stream;}
public int read(){if (numChars==-1) throw new InputMismatchException();if (curChar >= numChars){curChar = 0;try{numChars = stream.read(buf);}catch (IOException e){throw new InputMismatchException(); }if(numChars <= 0)return -1;}return buf[curChar++];}
public String nextLine(){String str = "";try{str = br.readLine();}catch (IOException e){e.printStackTrace();}return str;}
public int nextInt(){int c = read(); while(isSpaceChar(c))c = read(); int sgn = 1; if (c == '-'){sgn = -1;c = read(); }int res = 0;do{if(c<'0'||c>'9') throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public long nextLong(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}long res = 0;do{if (c < '0' || c > '9')throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public double nextDouble(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}double res = 0;while (!isSpaceChar(c) && c != '.'){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')
throw new InputMismatchException();res *= 10;res += c - '0';c = read();}if (c == '.'){c = read();double m = 1;while (!isSpaceChar(c)){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')throw new InputMismatchException();m /= 10;res += (c - '0') * m;c = read();}}return res * sgn;}
public String readString(){int c = read();while (isSpaceChar(c))c = read();StringBuilder res = new StringBuilder();do{res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public boolean isSpaceChar(int c){if (filter != null)return filter.isSpaceChar(c);return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;}
public String next(){return readString();}
public interface SpaceCharFilter{public boolean isSpaceChar(int ch);}
}
public static void main(String args[]) throws Exception{new Thread(null, new Solution(),"Main",1<<27).start();}
public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
public static int findGCD(int arr[], int n) { int result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result);return result; }
static void sortbycolomn(long arr[][], int col)
{
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(final long[] entry1,final long[] entry2) {
if (entry1[col] > entry2[col])return 1;
else return -1;
}
});
}
static long fii(int a,long[] fibo){
if(fibo[a]!=0)
return fibo[a];
fibo[a]=(long)(fii(a-1,fibo)%1000000007 + fii(a-2,fibo)%1000000007);
return fibo[a];
}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t=in.nextInt();
while(t--!=0){
int n=in.nextInt();
char[][] c=new char[n][];
for(int i=0;i<n;i++)
c[i]=in.next().toCharArray();
int count=0;
int z=0;
int odd=0;
for(int i=0;i<n;i++){
if(c[i].length%2==0){
z=0;
for(int j=0;j<c[i].length;j++){
if(c[i][j]=='0') z++;
}
if(z%2!=0)
count++;
}
else
odd=1;
}
if(count%2==0)
w.println(n);
else if(odd==1)
w.println(n);
else
w.println(n-1);
}
w.flush();
w.close();
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | de4933c5ae757598a0a6a9d0f03ff4de | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
public class TaskB {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int q = s.nextInt();
while(q-- > 0) {
int n = s.nextInt();
int zero = 0;
int one = 0;
int[] lengths = new int[n];
for(int i=0;i<n;i++) {
char[] str = s.next().toCharArray();
lengths[i] = str.length;
for(int x=0;x<str.length;x++) {
if(str[x] == '0') {
zero++;
} else {
one++;
}
}
}
int jo = 0;
int jz = 0;
int jo1 = 0;
int jz1 = 0;
//System.out.println(zero + " " + one);
int last = -1;
for(int i=0;i<n;i++) {
int curr = lengths[i];
if(zero - curr >= 0) {
jo += curr/2;
jo1 += curr%2;
zero -= curr;
} else if(one - curr >= 0) {
jz += curr/2;
jz1 += curr%2;
one -= curr;
} else {
last = curr;
}
}
if(last%2 == 0) {
if(zero%2 == 0 && one%2 == 0) {
System.out.println(n);
} else {
if(jo1 > 0 || jz1 > 0) {
System.out.println(n);
} else {
System.out.println(n-1);
}
}
} else {
System.out.println(n);
}
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | e00ad6ac56101b1fb067071e851cc391 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.*;
import javax.lang.model.util.ElementScanner6;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
class pair implements Comparable<pair>{
int i;
int cnt;
public pair(int i,int cnt)
{
this.i=i;
this.cnt=cnt;
}
public int compareTo(pair p)
{
return Long.compare(this.i,p.i);
}
}
class Node implements Comparable < Node > {
int i;
int cnt;
Node(int i, int cnt) {
this.i = i;
this.cnt = cnt;
}
public int compareTo(Node n) {
if (this.cnt == n.cnt) {
return Integer.compare(this.i, n.i);
}
return Integer.compare(this.cnt, n.cnt);
}
}
public boolean done(int[] sp, int[] par) {
int root;
root = findSet(sp[0], par);
for (int i = 1; i < sp.length; i++) {
if (root != findSet(sp[i], par))
return false;
}
return true;
}
public int findSet(int i, int[] par) {
int x = i;
boolean flag = false;
while (par[i] >= 0) {
flag = true;
i = par[i];
}
if (flag)
par[x] = i;
return i;
}
public void unionSet(int i, int j, int[] par) {
int x = findSet(i, par);
int y = findSet(j, par);
if (x < y) {
par[y] = x;
} else {
par[x] = y;
}
}
public long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
public boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public void minPrimeFactor(int n, int[] s) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
s[1] = 1;
s[2] = 2;
for (int i = 4; i <= n; i += 2) {
prime[i] = false;
s[i] = 2;
}
for (int i = 3; i <= n; i += 2) {
if (prime[i]) {
s[i] = i;
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
s[j] = i;
}
}
}
}
public void findAllPrime(int n, ArrayList < Node > al, int s[]) {
int curr = s[n];
int cnt = 1;
while (n > 1) {
n /= s[n];
if (curr == s[n]) {
cnt++;
continue;
}
Node n1 = new Node(curr, cnt);
al.add(n1);
curr = s[n];
cnt = 1;
}
}
public int binarySearch(int n, int k) {
int left = 1;
int right = 100000000 + 5;
int ans = 0;
while (left <= right) {
int mid = (left + right) / 2;
if (n / mid >= k) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
public boolean checkPallindrom(String s) {
char ch[] = s.toCharArray();
for (int i = 0; i < s.length() / 2; i++) {
if (ch[i] != ch[s.length() - 1 - i])
return false;
}
return true;
}
public void remove(ArrayList < Integer > [] al, int x) {
for (int i = 0; i < al.length; i++) {
for (int j = 0; j < al[i].size(); j++) {
if (al[i].get(j) == x)
al[i].remove(j);
}
}
}
public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public void printDivisors(long n, ArrayList < Long > al) {
// Note that this loop runs till square root
for (long i = 1; i*i <= (n); i++) {
if (n % i == 0) {
// If divisors are equal, print only one
if (n / i == i) {
al.add(i);
} else // Otherwise print both
{
al.add(i);
al.add(n / i);
}
}
}
}
public static long constructSegment(long seg[], long arr[], int low, int high, int pos) {
if (low == high) {
seg[pos] = arr[low];
return seg[pos];
}
int mid = (low + high) / 2;
long t1 = constructSegment(seg, arr, low, mid, (2 * pos) + 1);
long t2 = constructSegment(seg, arr, mid + 1, high, (2 * pos) + 2);
seg[pos] = t1 + t2;
return seg[pos];
}
public static long querySegment(long seg[], int low, int high, int qlow, int qhigh, int pos) {
if (qlow <= low && qhigh >= high) {
return seg[pos];
} else if (qlow > high || qhigh < low) {
return 0;
} else {
long ans = 0;
int mid = (low + high) / 2;
ans += querySegment(seg, low, mid, qlow, qhigh, (2 * pos) + 1);
ans += querySegment(seg, mid + 1, high, qlow, qhigh, (2 * pos) + 2);
return ans;
}
}
public static int lcs(char[] X, char[] Y, int m, int n) {
if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
else
return Integer.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
public static long recursion(long start, long end, long cnt[], int a, int b) {
long min = 0;
long count = 0;
int ans1 = -1;
int ans2 = -1;
int l = 0;
int r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] >= start) {
ans1 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
l = 0;
r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] <= end) {
ans2 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
if (ans1 == -1 || ans2 == -1 || ans2 < ans1) {
// System.out.println("min1 "+min);
min = a;
return a;
} else {
min = b * (end - start + 1) * (ans2 - ans1 + 1);
}
if (start == end) {
// System.out.println("min "+min);
return min;
}
long mid = (end + start) / 2;
min = Long.min(min, recursion(start, mid, cnt, a, b) + recursion(mid + 1, end, cnt, a, b));
// System.out.println("min "+min);
return min;
}
public int dfs_util(ArrayList < Integer > [] al, boolean vis[], int x, int[] s, int lvl[]) {
vis[x] = true;
int cnt = 1;
for (int i = 0; i < al[x].size(); i++) {
if (!vis[al[x].get(i)]) {
lvl[al[x].get(i)] = lvl[x] + 1;
cnt += dfs_util(al, vis, al[x].get(i), s, lvl);
}
}
s[x] = cnt;
return s[x];
}
public void dfs(ArrayList[] al, int[] s, int[] lvl) {
boolean vis[] = new boolean[al.length];
for (int i = 0; i < al.length; i++) {
if (!vis[i]) {
lvl[i] = 1;
dfs_util(al, vis, i, s, lvl);
}
}
}
public int[] computeLps(String s)
{
int ans[] =new int[s.length()];
char ch[] = s.toCharArray();
int n = s.length();
int i=1;
int len=0;
ans[0]=0;
while(i<n)
{
if(ch[i]==ch[len])
{
len++;
ans[i]=len;
i++;
}
else
{
if(len!=0)
{
len=ans[len-1];
}
else
{
ans[i]=len;
i++;
}
}
}
return ans;
}
private void solve(InputReader inp, PrintWriter out1) {
int t = inp.nextInt();
for(int k=0; k<t;k++)
{
int odd=0;
int bad=0;
int ans=0;
int n = inp.nextInt();
String s[] = new String[n];
for(int i=0;i<n;i++)
{
s[i] = inp.next();
}
for(int i=0;i<n;i++)
{
if(s[i].length()%2==0)
{
char ch[] = s[i].toCharArray();
int cnt = 0;
for(int j=0;j<ch.length;j++)
{
if(ch[j]=='1')
{
cnt++;
}
}
if(cnt%2==1)
{
bad++;
}
else
{
ans++;
}
}
else
{
odd++;
}
}
if(odd>=1)
{
ans+=bad;
ans+=odd;
}
else
{
if(bad%2==0)
{
ans+=bad;
}
else
{
ans+=bad-1;
}
}
out1.println(ans);
}
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
class ele implements Comparable < ele > {
int value;
int i;
boolean flag;
public ele(int value, int i) {
this.value = value;
this.i = i;
this.flag = false;
}
public int compareTo(ele e) {
return Integer.compare(this.value, e.value);
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 35afcdfffe50cd26d2c1c08011aad5d4 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ijxjdjd
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int Q = in.nextInt();
for (int iter = 0; iter < Q; iter++) {
int N = in.nextInt();
int[] need = new int[50];
int ones = 0;
int zeros = 0;
ArrayList<Integer> sizes = new ArrayList<>();
int oddCount = 0;
for (int i = 0; i < N; i++) {
char[] s = in.next().toCharArray();
sizes.add(s.length);
for (int j = 0; j < s.length; j++) {
if (s[j] == '1') {
zeros++;
} else {
ones++;
}
}
if (s.length % 2 == 1) {
oddCount++;
}
}
int ans = N;
if (oddCount == 0 && zeros % 2 == 1 && ones % 2 == 1) {
ans--;
}
out.println(ans);
}
}
}
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 | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | c91f15e28caab52d4c5d63a6a61f9b2d | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class p1251B {
public void realMain() throws Exception {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000);
String in = fin.readLine();
String[] ar = in.split(" ");
int T = Integer.parseInt(ar[0]);
for(int t = 0; t < T; t++) {
in = fin.readLine();
int n = Integer.parseInt(in);
int num0 = 0;
int num1 = 0;
int[] lens = new int[n];
int numodd = 0;
int numdoubleeven = 0;
int numevenodd = 0;
for(int i = 0; i < n; i++) {
in = fin.readLine();
lens[i] = in.length();
num0 = 0;
num1 = 0;
for(int j = 0; j < lens[i]; j++) {
if(in.charAt(j) == '0') {
num0++;
} else {
num1++;
}
}
if(lens[i] % 2 == 1) {
numodd++;
} else {
if(num0 % 2 == 0) {
numdoubleeven++;
} else {
numevenodd++;
}
}
}
int ret = 0;
if(numodd > 0) {
ret = n;
} else if(numevenodd % 2 == 0) {
ret = n;
} else {
ret = n - 1;
}
/*
for(int i = 0; i < n; i++) {
if(lens[i] % 2 == 0) {
if(num0 % 2 == 0) {
int tmp = Math.min(lens[i], num0);
num0 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
num1 -= lens[i];
}
ret++;
} else if(num1 % 2 == 0) {
int tmp = Math.min(lens[i], num1);
num1 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
num0 -= lens[i];
}
ret++;
} else {
if(num0 > num1) {
int tmp = Math.min(lens[i], num0);
num0 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
ret--;
num1 -= lens[i];
}
ret++;
} else {
int tmp = Math.min(lens[i], num1);
num1 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
num0 -= lens[i];
ret--;
}
ret++;
}
}
} else {
if(num0 % 2 == 1) {
int tmp = Math.min(lens[i], num0);
num0 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
num1 -= lens[i];
}
ret++;
} else if(num1 % 2 == 1) {
int tmp = Math.min(lens[i], num1);
num1 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
num0 -= lens[i];
}
ret++;
} else {
if(num0 > num1) {
int tmp = Math.min(lens[i], num0);
num0 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
num1 -= lens[i];
}
ret++;
} else {
int tmp = Math.min(lens[i], num1);
num1 -= tmp;
lens[i] -= tmp;
if(lens[i] > 0) {
num0 -= lens[i];
}
ret++;
}
}
}
}*/
System.out.println(ret);
}
}
public static void main(String[] args) throws Exception {
p1251B a = new p1251B();
a.realMain();
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 2ed8e24d035636da47d77fc4af1b997f | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class ProblemB {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int a = in.nextInt();
for (int i = 0; i < a; i++) {
int n = in.nextInt();
int credit = 0;
int unb = 0;
for (int j = 0; j < n; j++) {
int ones = 0, zeros = 0;
char[] c = in.next().toCharArray();
for (int k = 0; k < c.length; k++) {
if (c[k] == '1') ones++;
else zeros++;
}
if (c.length % 2 == 0 && ones % 2 != 0) unb++;
if (c.length % 2 != 0) credit++;
}
boolean b = false;
if (unb % 2 != 0 && credit==0) b = true;
out.println(b ? n-1 : n);
}
out.flush();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | fe7a9c701a50730a52b094895f40db41 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution implements Runnable
{
static class InputReader
{
private InputStream stream;private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream){this.stream = stream;}
public int read(){if (numChars==-1) throw new InputMismatchException();if (curChar >= numChars){curChar = 0;try{numChars = stream.read(buf);}catch (IOException e){throw new InputMismatchException(); }if(numChars <= 0)return -1;}return buf[curChar++];}
public String nextLine(){String str = "";try{str = br.readLine();}catch (IOException e){e.printStackTrace();}return str;}
public int nextInt(){int c = read(); while(isSpaceChar(c))c = read(); int sgn = 1; if (c == '-'){sgn = -1;c = read(); }int res = 0;do{if(c<'0'||c>'9') throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public long nextLong(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}long res = 0;do{if (c < '0' || c > '9')throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public double nextDouble(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}double res = 0;while (!isSpaceChar(c) && c != '.'){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')
throw new InputMismatchException();res *= 10;res += c - '0';c = read();}if (c == '.'){c = read();double m = 1;while (!isSpaceChar(c)){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')throw new InputMismatchException();m /= 10;res += (c - '0') * m;c = read();}}return res * sgn;}
public String readString(){int c = read();while (isSpaceChar(c))c = read();StringBuilder res = new StringBuilder();do{res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public boolean isSpaceChar(int c){if (filter != null)return filter.isSpaceChar(c);return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;}
public String next(){return readString();}
public interface SpaceCharFilter{public boolean isSpaceChar(int ch);}
}
public static void main(String args[]) throws Exception{new Thread(null, new Solution(),"Main",1<<27).start();}
public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
public static int findGCD(int arr[], int n) { int result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result);return result; }
static void sortbycolomn(long arr[][], int col)
{
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(final long[] entry1,final long[] entry2) {
if (entry1[col] > entry2[col])return 1;
else return -1;
}
});
}
static long fii(int a,long[] fibo){
if(fibo[a]!=0)
return fibo[a];
fibo[a]=(long)(fii(a-1,fibo)%1000000007 + fii(a-2,fibo)%1000000007);
return fibo[a];
}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t=in.nextInt();
while(t--!=0){
int n=in.nextInt();
char[][] c=new char[n][];
for(int i=0;i<n;i++)
c[i]=in.next().toCharArray();
int count=0;
int z=0;
int odd=0;
for(int i=0;i<n;i++){
if(c[i].length%2==0){
z=0;
for(int j=0;j<c[i].length;j++){
if(c[i][j]=='0') z++;
}
if(z%2!=0)
count++;
}
else
odd=1;
}
if(count%2==0)
w.println(n);
else if(odd==1)
w.println(n);
else
w.println(n-1);
}
w.flush();
w.close();
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | e649f0eac075e9115f0d3b473dd3563c | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
while(t != 0){
t--;
int n = input.nextInt();
int flag = 0 , cnt =0;
for(int i = 0 ; i < n ; i++){
String s = input.next();
if(s.length()%2==1){
flag = 1;
continue;
}
for(int j = 0 ; j < s.length() ; j++){
if(s.charAt(j)=='0')cnt++;
}
}
if(flag == 0 && cnt%2==1){
System.out.println(n-1);
}
else{
System.out.println(n);
}
}
input.close();
System.exit(0);
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 934a918fa30eafa03a0e2bb32cd96df4 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
void solve(InputReader in, PrintWriter out) {
int q = in.nextInt();
while (q-->0) {
int n = in.nextInt();
int ans = 0;
int alt = 0;
int odd = 0;
for (int i = 0; i < n; ++i) {
int[] cnt = new int[2];
char[] arr = in.next().toCharArray();
for (char c : arr) {
cnt[c - '0']++;
}
boolean pal = false;
if (arr.length % 2 == 0) {
pal = cnt[0] % 2 == 0 && cnt[1] % 2 == 0;
} else {
pal = cnt[0] % 2 == 0 && cnt[1] % 2 == 1;
pal |= cnt[0] % 2 == 1 && cnt[1] % 2 == 0;
}
if (pal) {
++ans;
if (arr.length % 2 == 1) ++odd;
}
else ++alt;
}
ans += alt - alt % 2;
int rem = alt % 2 ;
ans += Math.min(rem, odd);
out.println(ans);
}
}
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Main solver = new Main();
solver.solve(in, out);
out.close();
}
static class InputReader {
BufferedReader in;
StringTokenizer st;
public InputReader(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | d1faf8fe471ded484b5f2d95480ba0c8 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
/* * */
public class E75B implements Runnable{
public static void main(String[] args) {
new Thread(null, new E75B(),"Main",1<<27).start();
}
@Override
public void run() {
FastReader fd = new FastReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = fd.nextInt();
for(int te = 0; te < t; te++){
int n = fd.nextInt();
String[] data = new String[n];
int ans = 0;
//ArrayList<Integer> indicies = new ArrayList<>();
int totalZ = 0, totalO = 0;
for(int i = 0; i < n; i++){
data[i] = fd.next();
for(int j = 0; j < data[i].length(); j++){
if(data[i].charAt(j) == '0')totalZ++;
else totalO++;
}
if(data[i].length() % 2 == 1){ ans++; }
}
int evens = n-ans;
if(totalO % 2 == 0 && totalZ % 2 == 0){
out.println(n);
}
else if(totalO % 2 == 1 && totalZ % 2 == 1){
if(ans == 0){
out.println(n-1);
}
else{
out.println(n);
}
}
else{
out.println(n);
}
}
out.close();
}
static class Value{
int z;
int o;
StringBuilder value;
public Value(String value) {
this.value = new StringBuilder(value);
}
}
//Helper functions
static int[] getArray(int n,boolean isSorted, FastReader fd){
int[] data = new int[n];
for(int i = 0; i < data.length; i++){ data[i] = fd.nextInt(); }
if(isSorted) Arrays.sort(data);
return data;
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public FastReader(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);
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 49a7e99af03ba53e9441d5ad87446e81 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tk;
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
int q = nextInt();
while (q-- > 0) {
int n = nextInt();
int bothodds = 0;
boolean flag = false;
for (int i = 0; i < n; i++) {
String s = nextStr();
if (!flag) {
if (s.length() % 2 == 1)
flag = true;
int ones = 0;
for (int j = 0; j < s.length(); j++)
if (s.charAt(j) == '1')
ones++;
if (ones % 2 == 1)
bothodds++;
}
}
if (flag)
out.println(n);
else
out.println(n - bothodds%2);
}
out.close();
}
static int nextInt() throws IOException {
try {
return Integer.parseInt(tk.nextToken());
} catch (NoSuchElementException | NullPointerException e) {
tk = new StringTokenizer(in.readLine());
return Integer.parseInt(tk.nextToken());
}
}
static String nextStr() throws IOException {
try {
return tk.nextToken();
} catch (NoSuchElementException | NullPointerException e) {
tk = new StringTokenizer(in.readLine());
return tk.nextToken();
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | d6435ea989807001f1ed4bc962093dc3 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes |
import java.util.Scanner;
public class BBB {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
for(int i=0;i<t;i++){
int n=scan.nextInt();
String ar[]=new String[n];
for(int j=0;j<n;j++) {
ar[j]=scan.next();
}
int ones=0;
int zeros=0;
int odlen=0;
for(int j=0;j<n;j++) {
if(ar[j].length()%2==1)odlen++;
for(int k=0;k<ar[j].length();k++) {
if(ar[j].charAt(k)=='0') {
zeros++;
}else {
ones++;
}
}
}
int x=zeros%2+ones%2;
if(x>odlen) {
System.out.println(n-1);
}else {
System.out.println(n);
}
}
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 77471bde56ac92f358fcd53993c48e82 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)throws IOException {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int q = in.nextInt();
int n;
String s;
boolean odd;
int val; int len;
for(int i=0;i<q;i++)
{
n=in.nextInt();
odd=false;
val=0;
for(int j=0;j<n;j++)
{
s=in.next();
len = s.length();
if(s.length()%2!=0)
odd=true;
if(!odd)
{
for(int k=0;k<len/2;k++)
{
val+=(s.charAt(k)==s.charAt(len-k-1)) ? 0 : 1;
}
}
}
// out.println("odd "+odd);
// out.println("yo "+val);
if(!odd && val%2!=0)
out.println(n-1);
else
out.println(n);
}
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 04f055e5fbb6f5ac220783341a20c427 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(reader.readLine());
for(int i=0; i < q; ++i) {
solve(reader);
}
} catch (IOException e) {
}
}
public static void solve(BufferedReader reader) throws IOException {
int n = Integer.parseInt(reader.readLine());
String s;
int odd = 0;
int evenGood = 0;
int evenBad = 0;
for(int i=0; i < n; ++i) {
s = reader.readLine();
if (s.length() % 2 == 1) {
++odd;
} else {
if (s.chars().filter(ch -> ch == '0').count() % 2 == 0) {
++evenGood;
}else{
++evenBad;
}
}
}
int k;
if(odd == 0 && evenBad % 2 == 1)
k = 1;
else
k = 0;
System.out.println(n - k);
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 80d8661212bcf2e92935de02c1ae18e9 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
static class pair implements Comparable<pair>{
int a,b;
pair(int x,int y){
a=x;b=y;
}
public int compareTo(pair t){
if(t.a==this.a)
return this.b-t.b;
return this.a-t.a;
}
}
// public static ArrayList<pair> bfs(String[] a,int r,int c){
// ArrayList<pair> ans=new ArrayList<>();
// Queue<pair> q=new LinkedList<>();
// int[][] dxy={{-1,0,1,0},{0,-1,0,1}};
// q.add(new pair(r,c));
// HashSet<String> h=new HashSet<>();
// while(!q.isEmpty()){
// pair f=q.poll();
// ans.add(f);h.add(f.a+" "+f.b);
// for(int i=0;i<4;i++){
// int dx=f.a+dxy[0][i];
// int dy=f.b+dxy[1][i];
// if(dx<0||dy<0||dx>=a.length||dy>=a.length||h.contains(dx+" "+dy)||
// a[dx].charAt(dy)=='1')
// continue;
// q.add(new pair(dx,dy));
// h.add(dx+" "+dy);
// }
// }
// return ans;
// }
/*
1 1 1 1 1
3 3 3
2 3 3 2 1 3
1
2 2 2 2
4 4 4 1 4
*/
public static int pow(int a, int n) {
long ans = 1;
long base = a;
while (n != 0) {
if ((n & 1) == 1) {
ans *= base;
ans %= 1000000007;
}
base = (base * base) % 1000000007;
n >>= 1;
}
return (int) ans % 1000000007;
}
public static int find(int x){
int i=1;int f=0;
while(x>0){
if((x&1)==0)f=i;
x>>=1;i++;
}
return f;
}
public static boolean good(int x){
if((((x+1)&x))==0)
return true;
return false;
}
public static long f(long n){
long val=2;
long preval=0;int i=1;
while(n>=val){
i++;
preval=val;
val=3*i+val-1;
}
return preval;
}
public static boolean bfs(ArrayList<Integer>[] a,int n,int[] b){
Queue<Integer> p=new LinkedList<>();
boolean v[]=new boolean[n];
v[0]=true;int k=0;
if(b[0]!=0)return false;
p.add(0);int c=1;
HashSet<Integer> h=new HashSet<Integer>();
h.add(0);
while(!p.isEmpty()){
int f=p.poll();k++;
if(h.contains(f))h.remove(f);
else return false;
v[f]=true;
c--;
for(int i:a[f]){
if(!v[i]){
p.add(i);v[i]=true;}
}
if(c==0){
c=p.size();
if(h.size()!=0)return false;
for(int j=k;j<k+p.size();j++)
h.add(b[j]);
}
}
return true;
}
public static int mi(int[] a,int k,int[] dp,int n){
int max=0;
for(int i=1;i*i<=k;i++){
// System.out.println("fact "+i);
if(k%i==0&&(a[i-1]<a[k-1])){
// System.out.println(i+" "+dp[i-1]+" "+a[i-1]+" ");
max=Math.max(dp[i-1],max);}
if(k%i==0&&(a[k/i-1]<a[k-1])){
// System.out.println(i+" "+dp[i-1]+" "+a[i-1]+" ");
max=Math.max(dp[k/i-1],max);}
}
return max;
}
public static void dfs(ArrayList<Integer> a[],boolean[] v,int n,int llllll){
v[n]=true;
llllll=Math.max(n,llllll);
// System.out.println(max);
for(int i=0;i<a[n].size();i++){
if(!v[a[n].get(i)]){
dfs(a,v,a[n].get(i),llllll);
}
}
}
public static int bfs(ArrayList<Integer>[] a,int n,int x){
boolean[] v=new boolean[n];
int ans=0;
Queue<Integer> q=new LinkedList<>();
q.add(x);
while(!q.isEmpty()){
int f=q.poll();
v[f]=true;
if(a[f].size()-1==0||a[f].size()==0)continue;
ans+=a[f].size()-1;
for(int i:a[f]){
if(!v[i]){
q.add(i);v[i]=true;
}
}
}
return ans;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
StringBuilder st=new StringBuilder();
while(t-- > 0) {
int n=s.nextInt();
String[]a=new String[n];int o =0,e=0;
for(int i=0;i<n;i++){
a[i]=s.next();
if(a[i].length()%2==0){
int oc=0;
for(int j=0;j<a[i].length();j++)
if(a[i].charAt(j)=='0')oc++;
if(oc%2!=0)e++;
}else o++;
}
int ans=n-((o>0||e%2==0)?0:1);
st.append(ans+"\n");
}
System.out.println(st);
/*
2
1
3
1
6
6 23 21
1 1000 0
2 1 2
0
40
41664916690999888
1
1 2
2 1 3
3 1 2 4
2 4 1 3 5
3 4 1 5 2 6
1 11
5 35
3 6
0 42
0 0
1 2
3 4
6 45 46
2 2 1
3 4 2
4 4 3
*/
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 97d51ffbaaa8d2f57620fd0ac9e7d9d8 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
public class A {
static int countZeroAndOne(String[] s) {
int zeroCount = 0;
int oneCount = 0;
int totalLength = 0;
int noOfOddString = 0;
for (int i = 0; i < s.length; i++) {
String temp = s[i];
if (temp.length() % 2 == 1) {
noOfOddString++;
}
totalLength = totalLength + temp.length();
for (int j = 0; j < temp.length(); j++) {
if (temp.charAt(j) == '0') {
zeroCount++;
} else {
oneCount++;
}
}
}
if (zeroCount % 2 == 1 && oneCount % 2 == 1) {
if (noOfOddString == 0 || noOfOddString % 2 == 1) {
return s.length - 1;
}
}
return s.length;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int queries = Integer.parseInt(sc.nextLine());
for (int i = 0; i < queries; i++) {
int noOfStr = Integer.parseInt(sc.nextLine());
String[] s = new String[noOfStr];
for (int j = 0; j < noOfStr; j++) {
s[j] = sc.nextLine();
}
int k = countZeroAndOne(s);
System.out.println(k);
}
// while (sc.hasNext()) {
// System.out.println(sc.nextLine());
// }
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | b18bdb9467d0be3848fedca7a2f67c0e | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class B2 {
static int N;
static char c[][];
static int dp[][];
static int total;
static int lenUntil[];
public static void main(String[] args) {
FS in = new FS();
int Q = in.nextInt();
for(int runs = 1; runs <= Q; runs++) {
N = in.nextInt();
c = new char[N][];
total = 0;
int ones = 0;
int zeros = 0;
for(int i = 0; i < N; i++) {
c[i] = in.next().toCharArray();
total += c[i].length;
for(char cc : c[i]) {
if(cc == '1') ones++;
else zeros++;
}
}
int res = 0;
for(int i = 0; i < N; i++) {
if(c[i].length%2 == 1) { res++; continue;}
for(int g1 = 0; g1 <= ones; g1++) {
int g0 = c[i].length - g1;
if(g0 > zeros) continue;
if(g1%2 == 0 && g0%2 == 0) {
res++;
ones-=g1;
zeros-=g0;
break;
}
}
}
System.out.println(res);
}
}
static int go(int id, int ones) {
if(id >= N) return 0;
if(dp[id][ones] != -1) return dp[id][ones];
int res = 0;
int zeros = total-lenUntil[id]-ones;
if(c[id].length%2 == 0) { //even len
for(int give = 0; give <= Math.min(2, ones); give++) {
int g1 = give;
int g0 = c[id].length - g1;
if(g0 > zeros) continue;
if(g1%2 == 0 && g0%2 == 0) res = Math.max(res, 1+go(id+1, ones-g1));
else res = Math.max(res, go(id+1,ones-g1));
}
}
else { //odd
for(int give = 0; give <= Math.min(2, ones); give++) {
int g1 = give;
int g0 = c[id].length - g1;
if(g0 > zeros) continue;
res = Math.max(res, 1+go(id+1,ones-g1));
}
}
return dp[id][ones] = res;
}
static class FS{
BufferedReader br;
StringTokenizer st;
public FS() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine());}
catch(Exception e) { throw null;}
}
return st.nextToken();
}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
}
static void sort(int a[]) {
ArrayList<Integer> list = new ArrayList<Integer>();
for(int ii : a) list.add(ii);
Collections.sort(list);
for(int i = 0; i < a.length; i++) a[i] = list.get(i);
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | b19fc16bac24ead04c60be542618db46 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nt = sc.nextInt();
for (int test = 0; test < nt; ++test) {
int n = sc.nextInt();
int num0 = 0, num1 = 0, numOdd = 0, numEven = 0;
for (int i = 0; i < n; ++i) {
String s = sc.next();
if (s.length() % 2 == 0) ++numEven;
else ++numOdd;
for (int j = 0; j < s.length(); ++j)
if (s.charAt(j) == '0') ++num0;
else ++num1;
}
if (num0 % 2 == 0 && num1 % 2 == 0) {
System.out.println(n);
} else if (num0 % 2 == 1 && num1 % 2 == 1) {
System.out.println(numOdd == 0 ? (n - 1) : n);
} else {
System.out.println(n);
}
}
sc.close();
}
}
| Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 4b3f50ffc3521e93429fcfe0dcc6d871 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
StringBuilder out=new StringBuilder();
StringTokenizer st=new StringTokenizer(br.readLine());
int t=Integer.parseInt(st.nextToken());
while(t-->0){
int n=Integer.parseInt(br.readLine());
int non_pali=0;
int pali=0;
int odd=0;
for(int i=0;i<n;i++){
String s=br.readLine();
int o=0,z=0;
for(int j=0;j<s.length();j++){
if(s.charAt(j)=='0')
o++;
else
z++;
}
if(o%2!=0 && z%2!=0)
non_pali++;
else{
pali++;
if(s.length()%2!=0)
odd++;
}
}
//System.out.println(pali+" "+non_pali+" "+odd);
int ans=pali+((non_pali/2)*2);
if(odd>0 && non_pali%2!=0)
ans++;
out.append(ans+"\n");
}
System.out.println(out);
}}
// class Graph
// {
// private int V; // No. of vertices
// // Array of lists for Adjacency List Representation
// LinkedList<Integer> adj[];
// // Constructor
// Graph(int v)
// {
// V = v;
// adj = new LinkedList[v];
// for (int i=0; i<v; ++i)
// adj[i] = new LinkedList();
// }
// //Function to add an edge into the graph
// void addEdge(int v, int w)
// {
// adj[v].add(w);
// adj[w].add(v);// Add w to v's list.
// }
// // A function used by DFS
// } | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 7aeecaca4a02874585b80899bf6ce242 | train_001.jsonl | 1571929500 | A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously? | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.regex.*;
public class vk18
{
public static void main(String[]stp) throws Exception
{
Scanner scan=new Scanner(System.in);
//PrintWriter pw = new PrintWriter(System.out);
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//String []s;
int q=scan.nextInt();
while(q!=0)
{
int n=scan.nextInt();
int a=0,b=0,d=0,i,j;
for(i=0;i<n;i++)
{
String s=scan.next();
char c[]=s.toCharArray();
if(s.length()%2==1) d++;
for(j=0;j<s.length();j++) { if(c[j]=='1') a++; else b++; }
}
if(d==0 && a%2==1) System.out.println(n-1);
else System.out.println(n);
q--;
}
}
} | Java | ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"] | 2 seconds | ["1\n2\n2\n2"] | NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$. | Java 8 | standard input | [
"greedy",
"strings"
] | 3b8678d118c90d34c99ffa9259cc611f | The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones. | 1,400 | Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case. | standard output | |
PASSED | 16a09031ad9b563c490b2442db78b201 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int h = sc.nextInt();
int m = sc.nextInt();
int hunger = sc.nextInt();
int d = sc.nextInt();
int cost = sc.nextInt();
int n = sc.nextInt();
double cc =0,c1=0;
if (h>=20)
{ cc = (double)cost-(double)cost*0.2;
c1 = Math.ceil((double)hunger/n);
c1*=cc;
}
else
{
c1 = Math.ceil((double)hunger/n);
c1*=cost;
}
int time =0;
if (h<=19)
{
while(h<19)
{
time+=60;
h++;
}
time+=60-m;
}
else
time=0;
hunger += d*time;
double newCost = (double)cost - 0.2*(double)cost;
double c2 = Math.ceil((double)hunger/n);
c2*=newCost;
System.out.println(Math.min(c1, c2));
sc.close();
}
} | Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | a122855ca6948c27300b6f35c636b46a | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.regex.Matcher;
import javax.swing.plaf.metal.MetalBorders.PaletteBorder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
public class Main implements Runnable{
LinkedList<Integer>[] g;
boolean[] visited;
LinkedList<Integer>[] values;
HashSet<Integer>[] sets ;
public static void main(String[] args) throws IOException {
new Thread(null , new Main(),"Main", 1<<26).start();
}
@SuppressWarnings("unchecked")
public void run(){
try {
PrintWriter out = new PrintWriter(System.out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
st = new StringTokenizer(br.readLine());
int hh = parseInt(st.nextToken());
int mm = parseInt(st.nextToken());
st= new StringTokenizer(br.readLine());
float H = parseInt(st.nextToken());
float D = parseInt(st.nextToken());
float C = parseInt(st.nextToken());
float N = parseInt(st.nextToken());
int time = hh * 60 + mm;
int solde = 20 * 60;
float priceBefore = (float) (Math.ceil(H / N) * C);
//int priceAfter;
if(time > solde) {
float p = (float) (Math.ceil(H / N) * C * 0.8);
out.printf("%.9f",Math.min(p, priceBefore));
}else {
int wait = solde - time;
H += wait * D;
float p = (float) (Math.ceil(H / N) * C * 0.8);
out.printf("%.9f",Math.min(p, priceBefore));
}
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | f94083036fba5e40a0e5537bc18885b4 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
ProblemAFeedTheCat solver = new ProblemAFeedTheCat();
solver.solve(1, in, out);
out.close();
}
static class ProblemAFeedTheCat {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int h = in.nextInt(), m = in.nextInt();
int H = in.nextInt(), D = in.nextInt();
int C = in.nextInt(), N = in.nextInt();
int time = Math.max(0, (20 - h) * 60 - m);
int toAdd = time * D;
double ans1 = (((H + toAdd) + (N - 1)) / N) * (0.8 * C);
double ans2 = (H + (N - 1)) / N * C;
out.println(Math.min(ans1, ans2));
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 32f7683b760f01dfed8bf06ac0c166f1 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
*
* @Maher Taho
*/
public class Level {
public static int getTime(int hh,int mm){
int result=0;
int h=20-hh-1;
int m=60-mm;
result=h*60+m;
return result;
}
public static void main(String[] args){
Scanner in = new Scanner();
int hh=in.nextInt();
int mm=in.nextInt();
double h=in.nextInt();
double d=in.nextInt();
double c=in.nextDouble();
double n=in.nextInt();
if(hh>=20){
//with disscount
double res=Math.ceil(h/n)*c*0.8;
System.out.println(String.format("%.4f",res));
}else{
//without
double now=Math.ceil(h/n)*c;
double newH=getTime(hh,mm)*d+h;
double wait= Math.ceil(newH/n)*c*0.8;
double min=Math.min(wait,now);
System.out.println(String.format("%.4f",min));
}
}
private static class Scanner
{
BufferedReader br;
StringTokenizer st;
public Scanner()
{
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;
}
}
private static class Stack {
private int Size;
Node top;
Stack(){
Size=0;
top=null;
}
public int size(){
return this.Size;
}
public void push(Object item){
Node node=new Node();
node.data=item;
node.next=top;
top=node;
Size++;
}
public void pop(){
if(top!=null)
top=top.next;
Size--;
}
public boolean isEmpty(){
return top==null;
}
public Object getTop(){
if(top!=null)
return top.data;
else
return null;
}
public void display(){
if(top!=null){
Node temp=top;
while(temp!=null){
System.out.print(temp.data+" ");
temp=temp.next;
}
System.out.println();
}
}
private class Node {
Object data;
Node next;
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 7cd6f5e274a7aa2622dbf237202d1f18 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.awt.List;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int hh=ni(), mm=ni();
double H=ni(), D=ni(), C=ni(), N=ni();
if(hh>=20) {
double x=Math.ceil(H/N)*C;
x-=x*0.2;
out.printf("%.14f",x);
}
else {
double x=Math.ceil(H/N)*C;
int d=20*60-hh*60-mm;
double y=Math.ceil((H+(d*D))/N)*C;
y-=y*0.2;
out.printf("%.14f",Math.min(x, y));
}
}
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 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 String nsl()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b) && b != ' '))
{ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b)))
{
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-')
{
minus = true;
b = readByte();
}
while(true)
{
if(b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
}else
{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-')
{
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
}else
{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o)
{ System.out.println(Arrays.deepToString(o)); }
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | bed1fee22f87a899da90bc17396950bb | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.awt.List;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
String hh=ns(), mm=ns();
double H=nd(), D=nd(), C=nd(), N=nd();
int h=Integer.parseInt(hh);
int m=Integer.parseInt(mm);
if(h>=20) {
int x=(int)(Math.ceil(H/N)*C);
double ans=x-(x*20/100.0);
out.printf("%.14f", ans);
}
else {
double x=Math.ceil(H/N)*C;
int minute=60*(20-(h+1))+(60-m);
int nh=(int)(H+minute*(int)D);
int y=(int)(Math.ceil(nh/N)*C);
double ans=y-(y*20/100);
double min=Math.min(ans, x);
out.printf("%.14f", min);
//tr(x,minute,nh,y,ans,min);
}
}
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 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 String nsl()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b) && b != ' '))
{ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b)))
{
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-')
{
minus = true;
b = readByte();
}
while(true)
{
if(b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
}else
{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-')
{
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
}else
{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o)
{ System.out.println(Arrays.deepToString(o)); }
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 1cb74b2f84a6c06f063e39687454692e | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.Scanner;
public class A471 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int ho = sc.nextInt();
int mi = sc.nextInt();
int hu = sc.nextInt();
int d = sc.nextInt();
int c = sc.nextInt();
int n = sc.nextInt();
int t = 0;
if(ho<20) {
t = 60-mi + 60*(19-ho);
}
if(t>0) {
int c1 = 0;
int c2 = 0;
if((hu+t*d)%n>0) {
if(hu%n>0) {
if(4.0*((hu+t*d)/n+1)/5 < hu/n + 1) {
c1 = 1;
}
}
else {
if(4.0*((hu+t*d)/n+1)/5 < hu/n) {
c1 = 1;
}
}
}
else {
if(hu%n>0) {
if(4.0*((hu+t*d)/n)/5 < hu/n+1) {
c1 = 1;
}
}
else {
if(4.0*((hu+t*d)/n)/5 < hu/n) {
c1 = 1;
}
}
}
if(c1 == 1) {
if((hu+t*d)%n>0) {
System.out.println(4.0*((hu+t*d)/n + 1)*c/5);
}
else {
System.out.println(4.0*((hu+t*d)/n)*c/5);
}
}
else {
if(hu%n>0)
System.out.println((hu/n + 1)*c);
else
System.out.println(hu*c/n);
}
}
else {
if(hu%n>0)
System.out.println((hu/n + 1)*c*4.0/5);
else
System.out.println(hu*c*4.0/(n*5));
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | ea33720db0c5882e660a422422a1c48f | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.Scanner;
public class feedCat {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int hours = in.nextInt();
int minutes = in.nextInt();
double H = in.nextDouble();
double D = in.nextDouble();
int C = in.nextInt();
double N = in.nextDouble();
double X = (H/N);
int otherBuns = (int) Math.ceil(X);
double otherCost = otherBuns*C;
if (hours >= 20 && hours < 24){
otherCost = otherBuns*0.8*C;
System.out.println(String.format("%.4f",otherCost));
}
if (hours < 20) {
int hourDifference = 20 - hours;
int minuteDifference = 60 - minutes;
int totalMinutes = 60 * (hourDifference - 1) + minuteDifference;
int totalBuns = (int) Math.ceil(((totalMinutes * D) + H) / N);
double totalCost = totalBuns*0.8*C;
if (totalCost < otherCost) {
System.out.println(String.format("%.4f",totalCost));
} else System.out.println(String.format("%.4f",otherCost));
}
}} | Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 402da5c4e9bec6f1030e3b81317b48a6 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double hh, mm, H, D, C, N, ris;
Scanner scanner = new Scanner(System.in);
hh = scanner.nextDouble();
mm = scanner.nextDouble();
H = scanner.nextDouble();
D = scanner.nextDouble();
C = scanner.nextDouble();
N = scanner.nextDouble();
ris = Math.ceil(H/N)*C;
if (hh < 20){
double tempo, prova;
tempo = 60*20 - hh*60 - mm;
prova = Math.ceil ((H + D * tempo)/N) * (C * 0.8);
if (prova < ris)
ris = prova;
}
else{
ris = Math.ceil (H/N) * (C * 0.8);
}
System.out.println(ris);
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | ba1995c16c4c3f0cc00e1493b9e269ee | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | //Author: Patel Rag
//Java version "1.8.0_211"
import java.util.*;
import java.io.*;
public class Main
{
public static Integer hh;
public static Integer mm;
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()); }
float nextFloat() { return Float.parseFloat(next()); }
boolean nextBoolean() { return Boolean.parseBoolean(next()); }
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long modExp(long x, long n, long mod) //binary Modular exponentiation
{
long result = 1;
while(n > 0)
{
if(n % 2 == 1)
result = (result%mod * x%mod)%mod;
x = (x%mod * x%mod)%mod;
n=n/2;
}
return result;
}
static long gcd(long a, long b)
{
if(a==0) return b;
return gcd(b%a,a);
}
static void nextTick()
{
mm = (mm + 1) % 60;
if(mm == 0)
{
hh = (hh + 1) % 24;
}
}
public static void main(String[] args)
throws IOException
{
FastReader fr = new FastReader();
hh = fr.nextInt();
mm = fr.nextInt();
double H = fr.nextDouble();
double D = fr.nextDouble();
double C = fr.nextDouble();
double N = fr.nextDouble();
double dis = 0.8000;
if(hh >= 20)
{
double out = Math.ceil(H/N)*C*dis;
System.out.println(out);
return;
}
double ans = Math.ceil(H/N)*C;
H = H + D;
nextTick();
while(hh <= 19)
{
//System.out.println(hh + " : " + mm);
double cost = Math.ceil(H/N)*C;
ans = Double.min(ans, cost);
H = H + D;
nextTick();
}
ans = Double.min(ans, Math.ceil(H/N)*C*dis);
System.out.println(ans);
}
}
class pair
{
public int first;
public int second;
public pair(int first,int second)
{
this.first = first;
this.second = second;
}
public int first() { return first; }
public int second() { return second; }
public void setFirst(int first) { this.first = first; }
public void setSecond(int second) { this.second = second; }
}
class myComp implements Comparator<pair>
{
public int compare(pair a,pair b)
{
return (a.first - b.first);
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 77f7fc50eb706f6db557ae047c60ac5d | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.StringTokenizer;
public class Main {
static double H, D, C, N;
static int hh, mm;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
hh = Integer.valueOf(st.nextToken());
mm = Integer.valueOf(st.nextToken());
st = new StringTokenizer(br.readLine());
H = Double.valueOf(st.nextToken()); D = Double.valueOf(st.nextToken());
C = Double.valueOf(st.nextToken()); N = Double.valueOf(st.nextToken());
double minPrice;
if (hh >= 20) {
minPrice = Math.ceil(H / N) * C * 0.8;
} else {
double price1 = Math.ceil(H / N) * C;
int minTillDiscount = (19 - hh) * 60 + (60 - mm);
double price2 = Math.ceil((H + minTillDiscount * D) / N) * C * 0.8;
minPrice = Math.min(price1, price2);
}
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
out.println(minPrice);
out.close();
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 61ce045ab0dfb826febbd763b9cbd46c | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.Scanner;
public class ProbA
{
public static void main(String[] agrs)
{
Scanner input = new Scanner(System.in);
double hours = input.nextInt();
double minutes = input.nextInt();
double hunger = input.nextInt();
double hungerPerMinute = input.nextInt();
double cost = input.nextInt();
double hungerPerBun = input.nextInt();
//int catHunger = ((hours * 60) + minutes) * hungerPerMinute;
if(hours >= 20)
{
System.out.println(Math.ceil((hunger/hungerPerBun)) * cost * .8);
}
else
{
double costToWait = ((20 * 60) - (hours * 60 + minutes)) * hungerPerMinute; //wait time till 20 in terms of hunger
if(Math.ceil((costToWait + hunger) / (hungerPerBun)) * .8 * cost > Math.ceil((hunger / hungerPerBun)) * cost)
{
System.out.println(Math.ceil((hunger / hungerPerBun)) * cost);
} else
{
System.out.println(Math.ceil(((costToWait + hunger) / (hungerPerBun))) * .8 * cost);
}
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | a588b51d97cf7a8b44b3bf4cf3e39c48 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.awt.Point;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.*;
import java.util.*;
public class Main {
//////
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//////
public static long modularExponentiation(long x, long n, long M) {
long result = 1;
while (n > 0) {
if (n % 2 == 1)
result = (result * x) % M;
x = (x * x) % M;
n = n / 2;
}
return result;
}
public static long modularExponentiation1(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1)
result = (result * x);
x = (x * x);
n = n / 2;
}
return result;
}
/////
static public int fun(int num) {
int prod = 1;
while (num > 0) {
if (num % 10 != 0) {
prod = prod * (num % 10);
}
num = num / 10;
}
return prod;
}
public static boolean dfs(int x, int find, boolean[] visited, int[][] matrix) {
boolean ans = false;
if (x == find) {
ans = true;
return true;
}
for (int i = 0; i < 26; i++) {
if (visited[i] == false && matrix[x][i] == 1) {
visited[i] = true;
ans = ans || dfs(i, find, visited, matrix);
}
}
return ans;
}
static int lis(int arr[], int n, int k, int b) {
int lis[] = new int[n];
int i, j, max = 0;
/* Initialize LIS values for all indexes */
for (i = 0; i < n; i++)
lis[i] = 1;
/* Compute optimized LIS values in bottom up manner */
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] >= k * arr[j] + b && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for (i = 0; i < n; i++)
if (max < lis[i])
max = lis[i];
return max;
}
public static void main(String[] args) throws IOException {
FastReader scan = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int A=scan.nextInt();
int B=scan.nextInt();
int H=scan.nextInt();
int D=scan.nextInt();
double C=scan.nextInt();
int N=scan.nextInt();
int diff=20-A;
if(B>=00&&diff!=0){
diff--;
}
diff=diff*60;
diff=diff+60-B;
diff=diff*D;
if(A>=20){
diff=0;
}
double max2=0,max3=0;
int mod1=0,mod2=0;
if(H%N==0){
mod1=0;
}else
mod1=1;
if((H+diff)%N==0){
mod2=0;
}else
mod2=1;
max2=(((((H)/N)+mod1))*C);
max3=((((((H+diff)/N)+mod2))*C)*.8);
System.out.println(Math.min(max2,max3));
}
} | Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | df16e7f26267a000d473732d8a046547 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
TaskAfeed solver = new TaskAfeed();
solver.solve(1, in, out);
out.close();
}
static class TaskAfeed {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int hh = in.nextInt(), mm = in.nextInt();
int h = in.nextInt(), d = in.nextInt(), c = in.nextInt(), n = in.nextInt();
long loda1 = Math.round((h * 1.0) / n);
if (loda1 * n >= h) {
loda1 = loda1;
} else {
loda1 = loda1 + 1;
}
double ans1 = (c) * loda1;
int min = 0;
double ans2 = 0;
double ans = 0, newc = c - (c * 0.2);
if (hh < 20) {
min = 60 - mm + (60 * (19 - hh));
int newh = (h + d * min);
long loda = Math.round((newh * 1.0) / n);
if (loda * n >= newh) {
loda = loda;
} else {
loda = loda + 1;
}
ans2 = (newc) * loda;
ans = Math.min(ans1, ans2);
} else {
long loda = Math.round((h * 1.0) / n);
if (loda * n >= h) {
loda = loda;
} else {
loda = loda + 1;
}
ans = (newc) * loda;
}
out.printf("%.4f", ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | d4d12cc9c6a6f677b5cdadcb1c095f4d | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] sachin32) {
Scanner in = new Scanner(System.in);
int hh = Integer.parseInt(in.next());
int mm = Integer.parseInt(in.next());
int H = in.nextInt();
int D = in.nextInt();
int C = in.nextInt();
int N = in.nextInt();
int time=0;
if(hh>=20) {
}
else time = (19-hh)*60 + (60-mm);
int bhoonkh = H + time*D;
int bun1 = H/N;
int bun2 = bhoonkh/N;
if(H%N>0) ++bun1;
if(bhoonkh%N>0) ++bun2;
double paisa = C * Math.min(bun1, 0.80*bun2);
System.out.format("%.4f", paisa);
System.out.println();
in.close();
}
} | Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 99dd4311b0dd029246ca74b808efe497 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.Scanner;
public class third471Div2 {
public static void main (String [] args){
Scanner sc = new Scanner( System.in);
int hh = sc.nextInt();
int mm = sc.nextInt();
int leftTime = (20-hh-1)*60 + (60-mm);
double H= sc.nextInt();
double D= sc.nextInt();
double C = sc.nextInt();
double N = sc.nextInt();
Double afterPrice = (Math.ceil((leftTime*D+H) / N)) * C*(80.0d /100.0d);
Double currPrice = (Math.ceil(H/N))* C;
if( leftTime < 0){
Double currPrice12 = ( Math.ceil(H/N) )* C *(80.0d /100.0d);
System.out.println(currPrice12);
}else{
if(afterPrice > currPrice){
System.out.println(currPrice);
}else{
System.out.println(afterPrice);
}
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | a94630de7d7616c22e52577458ed8ce7 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes |
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int h=s.nextInt();
int m=s.nextInt();
int ch=s.nextInt();
int d=s.nextInt();
double c=s.nextDouble();
int n=s.nextInt();
if(h<20)
{
int noofminutes=0;
int wake=ch%n==0?ch/n:ch/n+1;
double firstcost=wake*c;
noofminutes=(20-h-1)*60+60-m;
int increase=noofminutes*d;
ch=ch+increase;
c=c-c*0.2;
int later=ch%n==0?ch/n:ch/n+1;
double secondcost=later*c;
System.out.println(secondcost>firstcost?firstcost:secondcost);
}
else
{
c=c-c*0.2;
int noofbuns=ch%n==0?ch/n:ch/n+1;
double ans=noofbuns*c;
System.out.println(ans);
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | ff10aef4b50b63f8cb1efd17d95bb4b4 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class codechef1 {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int hh=scan.nextInt();
int mm=scan.nextInt();
int H=scan.nextInt();
int D=scan.nextInt();
int C=scan.nextInt();
int N=scan.nextInt();
float ans=0;
if(hh>=20) {
int n;
if(H%N ==0 ) {
n=H/N;
}else {
n=(H/N)+1;
}
ans= n* C;
ans=(float) (ans- (0.20) *(ans));
System.out.printf("%.4f",ans);
}
else {
float cost1=0;
int minutes= (20 -hh )*60 -mm;
int H1=H + D*minutes;
int n1;
if(H1%N==0) {
n1= H1/N;
}else {
n1= (H1/N)+1;
}
cost1= n1*C;
cost1=(float) (cost1 - (0.20)*(cost1));
float cost2;
int n2;
if(H%N==0) {
n2=H/N;
}else {
n2=(H/N)+1;
}
cost2= n2*C;
float ans1=Math.min(cost1, cost2);
System.out.printf("%.4f",ans1);
}
}
} | Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 4fa94c5143778216b5388701115eeb55 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[])
{
// String s=fs.next();
//char c[]=s.toCharArray();
//int len=s.length();
InputStream in=System.in;
FastScanner fs=new FastScanner(in);
PrintWriter out=new PrintWriter(System.out);
long hh=fs.nextInt();
long mm=fs.nextInt();
long h,d,c,n;
h=fs.nextInt();
d=fs.nextInt();
c=fs.nextInt();
n=fs.nextInt();
long hh1=0;
long mm1=0;
if(hh>=20)
{ hh1=0;
mm1=0;
}
else
{ hh1=19-hh;
mm1=60-mm;
}
if(mm1==60)
{
hh1++;
mm1=0;
}
double ans1=h+(60*hh1)*d+mm1*d;
double ans2=h;
double cost=(c*8.0)/10.0;
ans1=Math.ceil(ans1/n)*cost;
ans2=Math.ceil(ans2/n)*c;
// out.println(ans1+" "+ans2);
out.println(Math.min(ans1,ans2));
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream f) {
try {
br = new BufferedReader(new InputStreamReader(f));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
char [] charArray()
{
return next().toCharArray();
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | e6be763bbac49e0a01fad5b6ee69671c | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.util.Scanner;
public class problem955A {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int h = console.nextInt();
int m = console.nextInt();
int hunger = console.nextInt();
int hungerIncr = console.nextInt();
int cost = console.nextInt();
int hungerDecr = console.nextInt();
int timediff;
if (h<20) {
h *= 60;
timediff = 20*60-h-m;
double res=0;
double temphunger=hunger;
//Immediate
while (temphunger > 0) {
temphunger-=hungerDecr;
res+=cost;
}
double tempres =0;
hunger+=hungerIncr*timediff;
// System.out.println(hunger);
while (hunger>0) {
hunger-=hungerDecr;
tempres+=(0.8*cost);
}
// System.out.println(tempres);
// System.out.println( res);
System.out.println(Math.min(tempres, res));
}
else {
double result = 0;
while (hunger>0) {
result+=0.8*cost;
hunger-=hungerDecr;
}
System.out.println(result);
}
}
} | Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | d53e4c8e339417dd609d6cf990f854f0 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
public class comp1 {
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
String hour = inp.next();
String min = inp.next();
int hunger = inp.nextInt();
int dHungerProMinute = inp.nextInt();
double cMoney = inp.nextDouble();
int nIndex = inp.nextInt();
/*
String hour = "00";
String min = "00";
int hunger = 1;
int dHungerProMinute = 1;
double cMoney = 100;
int nIndex = 1;
*/
// System.out.println("This is hours " + hour+ ":"+min+ "hunger"+ hunger+ "pro minute hunger"+dHungerProMinute+"money pro bulochka"+cMoney+"how much hunger decreases the bulochka"+nIndex);
int minute = Integer.parseInt(min);
int hours = Integer.parseInt(hour);
//System.out.println(minute);
double price;
boolean waiting = false;
price = PriceCount (hunger,cMoney,nIndex,waiting);
//System.out.println(price);// 25500 should be
int waitingTime = 0;
int waitingMin = 0;
if (minute == 0){
waitingTime = 20-hours;
if (waitingTime < 0) {
waitingTime = 24 - waitingTime;
}
}
else
{
waitingMin = 60 - minute;
waitingTime= 19 - hours;
if (waitingTime < 0)
waitingTime=24 -waitingTime;
}
int newTime= waitingTime*60+waitingMin;
int newHunger = newTime*dHungerProMinute;
int hunger1=hunger+newHunger;
//System.out.println(hunger);
waiting = true;
double priceW = PriceCount (hunger1,cMoney,nIndex,waiting);
NumberFormat formatter = new DecimalFormat("#0.0000");
if (hours>=20 && hours<24){
waiting=true;
price= PriceCount (hunger,cMoney,nIndex,waiting);
// System.out.println("we are here");
}
// System.out.println("price " + price + " priceW = "+priceW);
if(price < priceW)
System.out.println(formatter.format(price));
else
System.out.println(formatter.format(priceW));
}
private static double PriceCount(int hunger,double price,int nIndex, boolean waiting){
double money=0;
double bulochkaAmount = (double)hunger / nIndex;
double bulochkaAmountR = Math.floor(bulochkaAmount);
if (bulochkaAmount>bulochkaAmountR)
bulochkaAmountR+=1;
int amount = (int) bulochkaAmountR;
if (waiting==false){
money = amount * price;
return money;
}
else {
price = price - (price * 0.2);
money = amount * price;
}
return money;
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 3c74368a6ec404dd6d17c30e76b6071d | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
AFeedTheCat solver = new AFeedTheCat();
solver.solve(1, in, out);
out.close();
}
static class AFeedTheCat {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
long hh = in.scanInt();
long mm = in.scanInt();
double ans = Double.MAX_VALUE;
long h = in.scanInt();
long d = in.scanInt();
long c = in.scanInt();
int n = in.scanInt();
// direct
ans = Math.min(ans, ((h / n) + (h % n != 0 ? 1 : 0)) * c);
//indirect
long minute = hh * 60 + mm;
if (minute <= 20 * 60) {
long hunger = (h + (20 * 60 - minute) * d);
ans = Math.min(ans, ((hunger / n) + (hunger % n != 0 ? 1 : 0)) * c * 0.8d);
} else {
long hunger = (h);
ans = Math.min(ans, ((hunger / n) + (hunger % n != 0 ? 1 : 0)) * c * 0.8d);
}
out.println(ans);
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 3bbb81484d40a93f9a449d10abfca69d | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ProblemAFeedTheCat solver = new ProblemAFeedTheCat();
solver.solve(1, in, out);
out.close();
}
static class ProblemAFeedTheCat {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
long hh = in.scanInt();
long mm = in.scanInt();
long H = in.scanInt();
long D = in.scanInt();
long C = in.scanInt();
long N = in.scanInt();
if (hh < 20) {
double ans = Math.ceil((double) H / N) * C;
H += D * (((20 - (hh + 1)) * 60) + (60 - mm));
ans = Math.min(ans, Math.ceil((double) H / (double) N) * (C - (0.2d * C)));
out.printf("%.9f", ans);
} else {
double temp = Math.ceil((double) H / (double) N);
double nc = (C - (0.2 * C));
double ans = nc * temp;
out.printf("%.49f", ans);
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 2b2925772e40dc4144d76b6d18a18eb0 | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.util.*;
public class Codeforces
{
static InputReader in = new InputReader(System.in);
static FastReader fr = new FastReader();
static OutputWriter out = new OutputWriter(System.out);
static int MOD = 1000000007, prime[];
static long gcd, x, y;
static boolean isPrime[];
static long nCr[][] = new long[1004][1004];
public static void main(String[] args) throws IOException
{
int hh = in.nextInt(), mm = in.nextInt(), H = in.nextInt(), D = in.nextInt(), C = in.nextInt(), N = in.nextInt();
DecimalFormat df = new DecimalFormat("#.####");
if(hh < 20) {
int min = ((20 - hh) * 60) - mm;
long total_hunger = H + (D * min);
long buns = total_hunger / N;
if(total_hunger % N != 0)
buns++;
double cost = buns * C * 0.8;
long buns1 = H / N;
if(H % N != 0)
buns1++;
//System.out.println(H/N);
double cost1 = buns1 * C;
if(cost < cost1)
System.out.print(Double.parseDouble(df.format(cost)));
else
System.out.print(Double.parseDouble(df.format(cost1)));
}
else {
long buns1 = H / N;
if(H % N != 0)
buns1++;
double cost = buns1 * C * 0.8;
System.out.print(Double.parseDouble(df.format(cost)));
}
}
static long min_3(long a, long b, long c)
{
if(a < b && a < c)
return a;
if(b < c)
return b;
return c;
}
static long max_3(long x, long y, long z)
{
if(x >= y && x >= z)
return x;
if(y >= x && y >= z)
return y;
return z;
}
static long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y/2, m) % m;
p = (p * p) % m;
return (y%2 == 0) ? p : (x * p) % m;
}
static void prime_sieve(int N)
{
isPrime = new boolean[N+1];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for(int i = 2; i*i <= N; i++)
{
if(isPrime[i]==true)
{
for(int j = 2*i; j <= N; j += i)
{
isPrime[j] = false;
prime[j] = i;
}
}
}
}
static void Calc_nCr()
{
for(int i = 0; i <= 1000; i++)
nCr[i][0] = 1;
for(int i = 1; i <= 1000; i++)
for(int j = 1; j <= 1000; j++)
nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % MOD;
}
static long factorial(long num)
{
long result = 1;
for(int i = 1; i <= num; i++)
result = result * (long)i;
return result;
}
static void ExtendedEuclidian(long a, long b)
{
if(b == 0)
{
gcd = a;
x = 1;
y = 0;
}
else
{
ExtendedEuclidian(b, a%b);
int temp = (int) x;
x = y;
y = temp - (a/b)*y;
}
}
static long GCD(long n, long m)
{
if(m != 0)
return GCD(m, n % m);
else
return n;
}
static class CustomComp implements Comparator<Object>
{
@Override
public int compare(Object o1, Object o2)
{
return 1;
}
}
static class Graph
{
private int V;
private LinkedList<Integer> adj[];
boolean visited[];
Graph(int v)
{
V = v;
//visited = new boolean[V];
adj = new LinkedList[V];
for(int i = 0; i < V; ++i)
adj[i] = new LinkedList<Integer>();
}
void addEdge(int v, int w)
{
adj[v].add(w);
adj[w].add(v);
}
// prints BFS traversal from a given source s
void BFS(int s)
{
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s] = true;
queue.add(s);
while (queue.size() != 0)
{
s = queue.poll();
System.out.print(s+" ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
int count = 0;
int DFS(int u, int v) {
visited = new boolean[26];
for(int i = 0; i < 26; i++) {
if(visited[i] == false) {
count = 0;
DFSUtil(i, u, v);
//System.out.println(i+" "+u+" "+v+" "+count);
if(count == 0 && visited[u] == true && visited[v] == true)
return 1;
if(count == 1 && (visited[u] == true || visited[v] == true))
return 1;
if(count == 2)
break;
}
}
return 0;
}
void DFSUtil(int s, int u, int v)
{
visited[s] = true;
//System.out.println(s);
if(s == u)
count++;
if(s == v)
count++;
if(count == 2)
return;
//System.out.println("count "+count);
Iterator<Integer> i = adj[s].listIterator();
while(i.hasNext())
{
int n = i.next();
if(!visited[n])
DFSUtil(n, u, v);
}
}
boolean isCyclicUndirectedUtil(int v, boolean visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;
Integer i;
// Recur for all the vertices adjacent to this vertex
Iterator<Integer> it = adj[v].iterator();
while (it.hasNext())
{
i = it.next();
// If an adjacent is not visited, then recur for that
// adjacent
if (!visited[i])
{
if (isCyclicUndirectedUtil(i, visited, v))
return true;
}
// If an adjacent is visited and not parent of current
// vertex, then there is a cycle.
else if (i != parent)
return true;
}
return false;
}
// Returns true if the graph contains a cycle, else false.
boolean isCyclicUndirected()
{
// Mark all the vertices as not visited and not part of
// recursion stack
boolean visited[] = new boolean[V];
// Call the recursive helper function to detect cycle in
// different DFS trees
for (int u = 1; u <= V; u++)
if (!visited[u]) // Don't recur for u if already visited
if (isCyclicUndirectedUtil(u, visited, -1))
return true;
return false;
}
boolean isCyclicDirectedUtil(int v, boolean visited[], boolean recStack[])
{
if(visited[v] == false)
{
// Mark the current node as visited and part of recursion stack
visited[v] = true;
recStack[v] = true;
// Recur for all the vertices adjacent to this vertex
Iterator<Integer> i = adj[v].listIterator();
while(i.hasNext())
{
int n = i.next();
if (!visited[n] && isCyclicDirectedUtil(n, visited, recStack))
return true;
else if (recStack[n])
return true;
}
}
recStack[v] = false; // remove the vertex from recursion stack
return false;
}
boolean isCyclicDirected()
{
boolean visited[] = new boolean[V];
boolean recStack[] = new boolean[V];
for(int i = 1; i <= V; i++)
if (isCyclicDirectedUtil(i, visited, recStack))
return true;
return false;
}
void topologicalSortUtil(int v, boolean visited[], Stack stack)
{
// Mark the current node as visited.
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
Iterator<Integer> it = adj[v].iterator();
while (it.hasNext()) {
int i = it.next();
if (!visited[i])
topologicalSortUtil(i, visited, stack);
}
// Push current vertex to stack which stores result
stack.push(new Integer(v));
}
// The function to do Topological Sort. It uses recursive topologicalSortUtil()
void topologicalSort()
{
Stack stack = new Stack();
// Mark all the vertices as not visited
boolean visited[] = new boolean[V];
// Call the recursive helper function to store Topological Sort starting from all
// vertices one by one
for (int i = 1; i <= V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack);
// Print contents of stack
while (stack.empty()==false)
System.out.print(stack.pop() + " ");
}
}
}
class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
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 OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object...objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
} | Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | 5be89bd035988957a11b237bf0bd142e | train_001.jsonl | 1521822900 | After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero. | 256 megabytes | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000 * 1000 * 1000 + 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() throws IOException {
int h = nextInt();
int m = nextInt();
int m1 = h * 60 + m;
int m2 = 20 * 60;
int H = nextInt();
int D = nextInt();
int C= nextInt();
int N = nextInt();
if (m1 < m2) {
double res = Integer.MAX_VALUE;
int cnt = H / N;
if (H % N != 0) {
cnt++;
}
int cost = cnt * C;
res = Math.min(res, cost);
int hunger = H + (m2 - m1) * D;
cnt = hunger / N;
if (hunger % N != 0) {
cnt++;
}
res = Math.min(res, cnt * C * 0.8);
outln(res);
}
else {
double res = Integer.MAX_VALUE;
int cnt = H / N;
if (H % N != 0) {
cnt++;
}
res = Math.min(res, cnt * C * 0.8);
outln(res);
}
}
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;
}
}
int gcd(int a, int b) {
while(a != 0 && b != 0) {
int c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"] | 1 second | ["25200.0000", "1365.0000"] | NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Java 8 | standard input | [
"greedy",
"math"
] | 937acacc6d5d12d45c08047dde36dcf0 | The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102). | 1,100 | Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | c633a18e7c69224a933f514f19958f96 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.util.*;
public class CD414A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt() , k = sc.nextInt();
if(k < n / 2 || (n == 1 && k > 0)) System.out.println(-1);
else if(k == n/2) {
for(int i = 1 ; i <= n ; i++ ) {
System.out.print(i + " ");
}
}else if(n ==1 && k==0) {
System.out.println(0);
}
else {
System.out.print((k - n/2 +1)+ " " + (2*(k - n/2 +1)) + " " );
if((k - n/2 +1) > n -2) {
for(int i = 1 ; i <= n - 2 ; i++ ) {
System.out.print(i + " ");
}
}
else {
for(int i = 1 ; i <= n - 2 ; i++ ) {
System.out.print( (2*(k - n/2 +1) + i) + " ");
}
}
}
sc.close();
}
}
| Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | c226922130689cb9205a48d931d0eba1 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
AMashmokhAndNumbers solver = new AMashmokhAndNumbers();
solver.solve(1, in, out);
out.close();
}
static class AMashmokhAndNumbers {
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int n = sc.nextInt();
int k = sc.nextInt();
if (n / 2 > k) {
pw.println(-1);
return;
}
int need = k - ((n / 2) - 1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n / 2; i++) {
if (i == 0) {
sb.append(need + " " + need * 2 + " ");
k -= need;
} else {
sb.append(((int) 1e9 - i * 2) + " " + ((int) (1e9) - (i * 2 + 1)) + " ");
k--;
}
}
if (n % 2 == 1)
sb.append((int) 1e9);
pw.println(k == 0 ? sb : -1);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | 2340585254423eb6dc539051fa8a0744 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static List<Integer> al = new ArrayList<>();
static {
}
private static void solver(InputReader sc, PrintWriter out) throws Exception {
int n = sc.nextInt();
int k = sc.nextInt();
int mid = n/2;
if(k==0){
if(n==1)
out.println(1);
else
out.println(-1);
return;
}
if(k < mid || mid==0)
out.println(-1);
else{
int ans = k-mid;
int l=0,m=0;
int counter=0;
if(ans > 0) {
counter+=2;
out.print((ans+1) + " " + ((ans+1) * 2)+" ");
mid--;
l = ans+1;
m = l * 2;
}
int count=mid*2;
int x=1;
while(counter != n){
if(x!=l && x!=m){
count--;
counter++;
out.print(x+" ");
}
x++;
}
// out.println("\n"+counter);
}
}
private static boolean isprime(int x){
int sq = (int)Math.sqrt(x);
for(int i=2; i<=sq; i++){
if(x%i==0)
return false;
}
return true;
}
private static boolean helper(long x){
double ans = Math.sqrt(x);
return ans%1!=0;
}
private static int gcd(int a, int b){
if(b==0)
return a;
return gcd(b, a%b);
}
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver(in,out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n){
int arr[] = new int[n];
for(int i=0;i<n;i++) arr[i] = nextInt();
return arr;
}
}
}
class Pair implements Comparable<Pair>{
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return x == pair.x &&
y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public int compareTo(Pair o) {
return this.x-o.x;
}
} | Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | 774b126c6dbb3b0e92bef009560280a1 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.util.*;
public class MashmokhandNumbers {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
if(n==1 ) {
if(k==0) {
System.out.println(1);
return;
}
if(k>=1) {
System.out.println(-1);
return;
}
}
if(k<n/2) {
System.out.println(-1);
}
else if(k==n/2) {
for(int i=1;i<=n;i++) {
System.out.print(i+" ");
}
}
else {
int temp = n-2;
int start= k-temp/2;
System.out.print(start+" ");
System.out.print(start*2+" ");
for(int i=1;i<=temp;i++) {
if(i==start || i==start*2) {
temp+=1;
i++;
}
System.out.print(i+" ");
}
}
}
}
| Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | f806aa4629107ba5de461a034dfd2781 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | // package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.sql.SQLOutput;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
// BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();//int n=Integer.parseInt(s.readLine());
int n=s.nextInt();int k=s.nextInt();
if(k<n/2||(n/2==0&&k>0)){
System.out.println(-1);
}
else if(n/2==0&&k==0) System.out.println(1);
else{int [] a=new int[n];int j=n-1;if(n%2!=0) j--;
int extra=k-n/2;HashMap<Integer,Integer> h=new HashMap<Integer, Integer>();
if(extra!=0){
// System.out.println(j);
extra++;
a[j]=extra;a[j-1]=extra*2;h.put(extra,1);h.put(extra*2,1);
int l=1;
for(int i=0;i<n;i++){
if(a[i]==0){
while(h.containsKey(l)) l++; a[i]=l;l++;
}
}
}else{
int l=1;
for(int i=0;i<n;i++){
if(a[i]==0){
a[i]=l;l++;
}
}
}
for(int i=0;i<n;i++) sb.append(a[i]+" ");
System.out.println(sb.toString() );
}
}
static void computeLPSArray(String pat, int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0;
while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if (len != 0) {
len = lps[len - 1];
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
static boolean isPrime(int n)
{
// Corner cas
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean isPrime(int n, int k)
{
// Corner cases
if (n <= 1 || n == 4) return false;
if (n <= 3) return true;
// Try k times
while (k > 0)
{
// Pick a random number in [2..n-2]
// Above corner cases make sure that n > 4
int a = 2 + (int)(Math.random() % (n - 4));
// Fermat's little theorem
if (power(a, n - 1, n) != 1)
return false;
k--;
}
return true;
}
static double power(double x, long y, int p) {
double 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;
}
public static void fracion(double x) {
String a = "" + x;
String spilts[] = a.split("\\."); // split using decimal
int b = spilts[1].length(); // find the decimal length
int denominator = (int) Math.pow(10, b); // calculate the denominator
int numerator = (int) (x * denominator); // calculate the nerumrator Ex
// 1.2*10 = 12
int gcd = (int)gcd((long)numerator, denominator); // Find the greatest common
// divisor bw them
String fraction = "" + numerator / gcd + "/" + denominator / gcd;
// System.out.println((denominator/gcd));
long x1=modInverse(denominator / gcd,998244353 );
// System.out.println(x1);
System.out.println((((numerator / gcd )%998244353 *(x1%998244353 ))%998244353 ) );
}static int max=Integer.MIN_VALUE;
static int max1=Integer.MIN_VALUE;static long[][] dp;static int[][] c;static int k=1;static int bhoo=0;
static int[] car;static int ans;static HashMap<Integer,Integer>[] ha;
public static void dfs(int ans2,int papa, int i, ArrayList<Integer>[] h, int[] vis,HashMap<Integer,Integer>[] bad) {
vis[i] = 1;
if(i!=1&&h[i].size()==1){
if(ans2!=-1) {ans++; sb1.append(ans2+" ");}
}
if(h[i]==null) return;
int hu=0;int hai=0;
for(Integer j:h[i]){
if(vis[j]==0&&bad[i].containsKey(j)) {
hai=1;break;
}
}int khi=0;
for(Integer j:h[i]) {//if(vis[j]==0) flag=1;
if(vis[j]==0){
if(!bad[i].containsKey(j)){
if(hai==0&&khi==0){khi=1; dfs(ans2,papa,j,h,vis,bad);}
else dfs(-1,papa,j,h,vis,bad);
}else{
if(hu==0){
if(papa==0){//ans++;//sb1.append(j+" ");
dfs(j,1,j,h,vis,bad);
}else{
hu=1;
dfs( j,1,j,h,vis,bad);}
}else{
// ans++;//sb1.append(j+" ");
dfs(j,1,j,h,vis,bad);
}
}
}
}//if(flag==1) bhoo=-1;
}static StringBuilder sb1=new StringBuilder();
public static void bfs(int i, HashMap<Integer, Integer>[] h, int[] vis, int len, int papa) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(i);
}
static int i(String a) {
return Integer.parseInt(a);
}
static long l(String a) {
return Long.parseLong(a);
}
static String[] inp() throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
return s.readLine().trim().split("\\s+");
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long modInverse(int a, int m)
{
{
// If a and m are relatively prime, then modulo inverse
// is a^(m-2) mode m
return (power(a, m - 2, m));
}
}
// To compute x^y under modulo m
static long power(int x, int y, int m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
// Function to return gcd of a and b
}
class Student
{
int l;int r;int i;
public Student(int l, int r,int i) {
this.l = l;
this.r = r;this.i=i;
}
// Constructor
// Used to print student details in main()
public String toString()
{
return this.l+" ";
}
}
class Sortbyroll implements Comparator<Student>
{
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b){
return a.l-b.l; }
} class Sortbyroll1 implements Comparator<Student>
{
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b){
return a.l-b.l;
}
} | Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | d566bf2d08138521dbf901922805ba68 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public final class MashMokAndNumbersCF {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String st[] = br.readLine().split(" ");
int n = Integer.parseInt(st[0]);
int k = Integer.parseInt(st[1]);
if (n == 1){
if(k==0)
System.out.println("1");
else
System.out.println("-1");
}else {
int pairs = n / 2;
if (k < pairs)
System.out.println("-1");
else {
int maxGcd = (k - (pairs - 1));
System.out.print(maxGcd + " " + 2 * maxGcd + " ");
int start = 1, i = 0;
while (i < pairs - 1) {
//System.out.println(i);
if (start != maxGcd && (start + 1) != maxGcd && start != 2 * maxGcd && (start + 1) != 2 * maxGcd) {
System.out.print(start + " " + (start + 1) + " ");
start++;
i++;
}
start++;
}
if (n % 2 != 0) {
while (start == maxGcd || start == 2 * maxGcd) {
start++;
}
System.out.println(start);
}
System.out.println();
}
}
}
}
| Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | 7db826e9d569f09c41cf09d82c477f4e | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static final int M = 1000000007;
static FastReader in = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
// static Scanner in = new Scanner(System.in);
// File file = new File("input.txt");
// Scanner in = new Scanner(file);
// PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
public static void main(String[] args) {
// int t = in.nextInt();
// while(t-- > 0){
long n = in.nextLong(), k = in.nextLong();
if(n/2 > k || (n==1 && k!=0)) {
out.print(-1);
}else if(n==1 && k==0){
out.print(1);
}else {
long rg=k-(n-2)/2;
List<Long> list = new ArrayList<>();
list.add(rg);
list.add(2*rg);
long last = 2*rg;
while(list.size() < n){
list.add(last+1);
last++;
}
for(long i : list) out.print(i+" ");
}
// }
out.close();
}
static int gcd(int a, int b) {
if(b==0) return a;
return gcd(b, a%b);
}
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 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | 55343756d6c48fe7b609916499ff5b09 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
if (n == 1 && k == 0) {
System.out.println("1");
return;
}
if (n / 2 > k || (n == 1 && k > 0)) {
System.out.println(-1);
return;
}
// [x, 2x] and (n-2) coprime pairs.
// k = x + (n - 2) / 2
int pairs = (n - 2) / 2;
int x = k - pairs;
int x2 = x * 2;
System.out.print(x + " " + x2 + " ");
int i = 1;
while (pairs > 0) {
if (i == x || i == x2 || (i + 1) == x || (i + 1) == x2) {
i++;
continue;
}
System.out.print(i + " " + (i + 1) + " ");
i += 2;
pairs--;
}
if (pairs == 0 && n % 2 == 1) {
for (int num = i; num < Integer.MAX_VALUE; num++) {
if (num == x || num == x2) continue;
System.out.print(num);
return;
}
}
}
} | Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | 07ede6ec7c93fd35258b9af5ab5171f2 | train_001.jsonl | 1396798800 | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109. | 256 megabytes | import java.util.*;
public class MashmokhAndNumbers
{
public static boolean isPrime(int x)
{
for (int i = 2; i <= Math.sqrt(x); i++)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner file = new Scanner(System.in);
int n = file.nextInt();
int k = file.nextInt();
file.close();
if (n / 2 > k || (n / 2 == 0 && k != 0))
{
System.out.println("-1");
return;
}
// Find the highest possible summation value
int N = n/2;
int max = 1;
while ((max * (max + 1.) / 2.) - ((max - N) * (max - N + 1.) / 2.) < k)
{
max++;
}
int[] valuesToAdd = new int[n/2];
Arrays.fill(valuesToAdd, 1);
int index = N - 1;
int numToGo = k-N; // Assume array is filled with 1s
while (numToGo > 0)
{
valuesToAdd[index] = Math.min(max - ((N - 1) - index), numToGo+1);
numToGo -= valuesToAdd[index]-1;
index--;
}
//System.out.println(Arrays.toString(valuesToAdd));
//System.out.println(N);
Set<Integer> used = new HashSet<Integer>();
List<Integer> answer = new ArrayList<Integer>();
int i;
// Do this for all the gcfs that are not 1
for (i = valuesToAdd.length - 1; i > -1 && valuesToAdd[i] != 1; i--)
{
int add = valuesToAdd[i]; // This is what we add every time
int multiple = valuesToAdd[i];
while (used.contains(multiple) || used.contains(multiple + add))
{
multiple += add;
}
answer.add(multiple);
answer.add(multiple + add);
used.add(multiple);
used.add(multiple + add);
}
//System.out.println(answer);
// We assume at this point foward that only 1s remain
int curUnvisited = 1;
for (; i > -1; i--)
{
while (used.contains(curUnvisited)) curUnvisited++;
int next = curUnvisited + 1;
while (used.contains(next)) next++;
if (next - curUnvisited == 1 || isPrime(next) || isPrime(curUnvisited))
{
answer.add(curUnvisited);
answer.add(next);
used.add(curUnvisited); // Might or might not be necesary
used.add(next); // Might or might not be necesary
}
else
{
i++; // Try again
}
curUnvisited = next + 1;
}
if (n % 2 == 1)
{
while (used.contains(curUnvisited)) curUnvisited++;
answer.add(curUnvisited);
}
format(answer);
//System.out.println(answer.size());
}
private static void format(List<Integer> answer)
{
for (int i = 0; i < answer.size(); i++)
{
if (i == answer.size() - 1)
{
System.out.println(answer.get(i));
}
else
{
System.out.print(answer.get(i) + " ");
}
}
}
}
| Java | ["5 2", "5 3", "7 2"] | 1 second | ["1 2 3 4 5", "2 4 3 7 1", "-1"] | Notegcd(x, y) is greatest common divisor of x and y. | Java 11 | standard input | [
"constructive algorithms",
"number theory"
] | b85c8bfbe67a23a81bef755f9313115a | The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108). | 1,500 | If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). | standard output | |
PASSED | 5328ac52db4ade9a35369babf683df26 | train_001.jsonl | 1571236500 | Consider a square grid with $$$h$$$ rows and $$$w$$$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $$$998\,244\,353$$$. | 512 megabytes | import java.io.*;
import java.util.*;
public class A {
FastScanner in;
PrintWriter out;
final int mod = 998244353;
int add(int x, int y) {
x += y;
return x >= mod ? (x - mod) : x;
}
int mul(int x, int y) {
return (int) (x * 1L * y % mod);
}
final int MAX = 3605;
int[][] c = new int[MAX][MAX];
void solve() {
c[0][0] = 1;
for (int i = 1; i < MAX; i++) {
c[i][0] = 1;
for (int j = 1; j < MAX; j++) {
c[i][j] = add(c[i - 1][j - 1], c[i - 1][j]);
}
}
int[] fact = new int[MAX];
fact[0] = 1;
for (int i = 1; i < MAX; i++) {
fact[i] = mul(fact[i - 1], i);
}
int h = in.nextInt();
int w = in.nextInt();
boolean[] rows = new boolean[h];
boolean[] cols = new boolean[w];
int n = in.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
rows[in.nextInt() - 1] = true;
cols[in.nextInt() - 1] = true;
}
}
int emptyRows = empty(rows);
int emptyCols = empty(cols);
int[] ways2rows = ways2(rows);
int[] ways2cols = ways2(cols);
int res = 0;
for (int cntVertical = 0; cntVertical < ways2rows.length; cntVertical++) {
for (int cntHorizontal = 0; cntHorizontal < ways2cols.length && cntVertical * 2 + cntHorizontal <= emptyRows && cntVertical + cntHorizontal * 2 <= emptyCols; cntHorizontal++) {
int ways = mul(ways2rows[cntVertical], c[emptyRows - cntVertical * 2][cntHorizontal]);
ways = mul(ways, mul(ways2cols[cntHorizontal], c[emptyCols - cntHorizontal * 2][cntVertical]));
ways = mul(ways, fact[cntVertical]);
ways = mul(ways, fact[cntHorizontal]);
res = add(res, ways);
}
}
out.println(res);
}
int empty(boolean[] a) {
int res = 0;
for (boolean z : a) {
res += z ? 0 : 1;
}
return res;
}
int[] ways2(boolean[] a) {
int n = a.length;
int[] dp = new int[n / 2 + 1];
int[] ndp = new int[dp.length];
dp[0] = 1;
for (int i = 0; i < a.length; ) {
if (a[i]) {
i++;
continue;
}
int j = i;
while (j != a.length && !a[j]) {
j++;
}
Arrays.fill(ndp, 0);
int len = j - i;
for (int cur = 0; cur < dp.length; cur++) {
if (dp[cur] == 0) {
continue;
}
for (int add = 0; add * 2 <= len; add++) {
ndp[cur + add] = add(ndp[cur + add], mul(dp[cur], c[len - add][add]));
}
}
int[] tmp = dp;
dp = ndp;
ndp = tmp;
i = j;
}
return dp;
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new A().runIO();
}
}
| Java | ["5 7 2\n3 1 3 2\n4 4 4 5", "5 4 2\n1 2 2 2\n4 3 4 4", "23 42 0"] | 2 seconds | ["8", "1", "102848351"] | NoteIn the first example, the initial grid looks like this:Here are $$$8$$$ ways to place zero or more extra dominoes to keep the placement perfectly balanced:In the second example, the initial grid looks like this:No extra dominoes can be placed here. | Java 8 | standard input | [
"dp",
"combinatorics"
] | 76fc2b718342821ac9d5a132a03c925e | The first line contains three integers $$$h$$$, $$$w$$$, and $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$), denoting the dimensions of the grid and the number of already placed dominoes. The rows are numbered from $$$1$$$ to $$$h$$$, and the columns are numbered from $$$1$$$ to $$$w$$$. Each of the next $$$n$$$ lines contains four integers $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$), denoting the row id and the column id of the cells covered by the $$$i$$$-th domino. Cells $$$(r_{i, 1}, c_{i, 1})$$$ and $$$(r_{i, 2}, c_{i, 2})$$$ are distinct and share a common side. The given domino placement is perfectly balanced. | 2,600 | Output the number of ways to place zero or more extra dominoes on the grid to keep the placement perfectly balanced, modulo $$$998\,244\,353$$$. | standard output | |
PASSED | bcbf74385c923ed2094c856019d9daed | train_001.jsonl | 1571236500 | Consider a square grid with $$$h$$$ rows and $$$w$$$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $$$998\,244\,353$$$. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author ilyakor
*/
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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
static final int mod = 998244353;
static final int maxn = 3650;
int[][] C;
int[] f;
public void solve(int testNumber, InputReader in, OutputWriter out) {
C = new int[maxn][maxn];
C[0][0] = 1;
for (int i = 1; i < maxn; ++i) {
C[i][0] = 1;
for (int j = 1; j < maxn; ++j) {
C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % mod;
}
}
f = new int[maxn];
f[0] = 1;
for (int i = 1; i < maxn; ++i) {
f[i] = (int) (((long) f[i - 1] * (long) i) % mod);
}
int n = in.nextInt();
int m = in.nextInt();
boolean[] u1 = new boolean[n];
boolean[] u2 = new boolean[m];
int cntK = in.nextInt();
for (int i = 0; i < cntK; ++i) {
int x1 = in.nextInt() - 1;
int y1 = in.nextInt() - 1;
int x2 = in.nextInt() - 1;
int y2 = in.nextInt() - 1;
u1[x1] = true;
u1[x2] = true;
u2[y1] = true;
u2[y2] = true;
}
int[] outt = new int[1];
int[] d1 = calc(u1, outt);
int cnt1 = outt[0];
int[] d2 = calc(u2, outt);
int cnt2 = outt[0];
long res = 0;
for (int i = 0; i < d1.length; ++i) {
if (d1[i] != 0) {
for (int j = 0; j < d2.length; ++j) {
if (d2[j] != 0) {
if (i * 2 + j > cnt1) {
continue;
}
if (i + j * 2 > cnt2) {
continue;
}
long cur = d1[i] * (long) d2[j];
cur %= mod;
cur *= C[cnt1 - i * 2][j];
cur %= mod;
cur *= C[cnt2 - j * 2][i];
cur %= mod;
cur *= f[j];
cur %= mod;
cur *= f[i];
cur %= mod;
res += cur;
res %= mod;
}
}
}
}
out.printLine(res);
}
private int[] calc(boolean[] u, int[] out) {
int n = u.length;
int[] d = new int[n / 2 + 1];
d[0] = 1;
int cur = 0;
int total = 0;
for (int i = 0; i < u.length; ++i) {
if (u[i]) {
if (cur > 1) {
add(d, cur);
}
cur = 0;
} else {
++cur;
++total;
}
}
if (cur > 1) {
add(d, cur);
}
out[0] = total;
return d;
}
private void add(int[] d, int cnt) {
for (int i = d.length - 1; i >= 0; --i) {
int val = d[i];
if (val == 0) {
continue;
}
for (int j = 1; j <= cnt / 2; ++j) {
long cur = C[cnt - j][j];
cur *= val;
d[i + j] = (int) ((d[i + j] + cur) % mod);
}
}
}
}
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 printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0) {
return -1;
}
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
}
| Java | ["5 7 2\n3 1 3 2\n4 4 4 5", "5 4 2\n1 2 2 2\n4 3 4 4", "23 42 0"] | 2 seconds | ["8", "1", "102848351"] | NoteIn the first example, the initial grid looks like this:Here are $$$8$$$ ways to place zero or more extra dominoes to keep the placement perfectly balanced:In the second example, the initial grid looks like this:No extra dominoes can be placed here. | Java 8 | standard input | [
"dp",
"combinatorics"
] | 76fc2b718342821ac9d5a132a03c925e | The first line contains three integers $$$h$$$, $$$w$$$, and $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$), denoting the dimensions of the grid and the number of already placed dominoes. The rows are numbered from $$$1$$$ to $$$h$$$, and the columns are numbered from $$$1$$$ to $$$w$$$. Each of the next $$$n$$$ lines contains four integers $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$), denoting the row id and the column id of the cells covered by the $$$i$$$-th domino. Cells $$$(r_{i, 1}, c_{i, 1})$$$ and $$$(r_{i, 2}, c_{i, 2})$$$ are distinct and share a common side. The given domino placement is perfectly balanced. | 2,600 | Output the number of ways to place zero or more extra dominoes on the grid to keep the placement perfectly balanced, modulo $$$998\,244\,353$$$. | standard output | |
PASSED | ecc46ff1d40ec01cda4558e8b1439de2 | train_001.jsonl | 1571236500 | Consider a square grid with $$$h$$$ rows and $$$w$$$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $$$998\,244\,353$$$. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
FSbalansirovannieRaspolozheniyaDomino solver = new FSbalansirovannieRaspolozheniyaDomino();
solver.solve(1, in, out);
out.close();
}
static class FSbalansirovannieRaspolozheniyaDomino {
int MOD = 998244353;
int[][] place2;
int[] calc2(boolean[] u) {
int n = u.length;
int[] res = new int[n / 2 + 1];
res[0] = 1;
int s = 0;
int f;
while (s < u.length) {
while (s < u.length && u[s]) {
s++;
}
if (s == u.length) {
break;
}
f = s + 1;
while (f < u.length && !u[f]) {
f++;
}
int seg = f - s;
for (int i = n / 2; i >= 0; i--) {
for (int j = 1; j * 2 <= seg && j <= i; j++) {
res[i] = (int) ((res[i] + ((long) res[i - j]) * place2[seg][j]) % MOD);
}
}
s = f;
}
return res;
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
int h = in.nextInt();
int w = in.nextInt();
boolean[] usedr = new boolean[h];
boolean[] usedc = new boolean[w];
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int x = in.nextInt() - 1;
usedr[x] = true;
x = in.nextInt() - 1;
usedc[x] = true;
x = in.nextInt() - 1;
usedr[x] = true;
x = in.nextInt() - 1;
usedc[x] = true;
}
int fr = 0;
for (int i = 0; i < h; i++) {
if (!usedr[i]) {
fr++;
}
}
int fc = 0;
for (int i = 0; i < w; i++) {
if (!usedc[i]) {
fc++;
}
}
int sz = Math.max(h, w);
place2 = new int[sz + 1][sz / 2 + 1];
place2[0][0] = place2[1][0] = 1;
for (int i = 2; i <= sz; i++) {
place2[i][0] = 1;
for (int j = 1; 2 * j <= sz; j++) {
place2[i][j] = (place2[i - 1][j] + place2[i - 2][j - 1]) % MOD;
}
}
int[][] ch = new int[sz + 1][sz + 1];
ch[0][0] = 1;
for (int i = 1; i <= sz; i++) {
ch[i][0] = 1;
for (int j = 1; j <= sz; j++) {
ch[i][j] = (ch[i - 1][j - 1] + ch[i - 1][j]) % MOD;
}
}
int[] h2 = calc2(usedr);
int[] v2 = calc2(usedc);
int[] fac = new int[sz + 1];
fac[0] = 1;
for (int i = 1; i <= sz; i++) {
fac[i] = (int) (((long) fac[i - 1]) * i % MOD);
}
long ans = 0;
for (int ha = 0; 2 * ha <= fc; ha++) {
for (int va = 0; 2 * va + ha <= fr && va + 2 * ha <= fc; va++) {
long num = ((long) h2[va]) * ch[fc - 2 * ha][va] % MOD * v2[ha] % MOD * ch[fr - 2 * va][ha] % MOD * fac[va] % MOD * fac[ha] % MOD;
ans = (ans + num) % MOD;
}
}
out.println(ans);
}
}
}
| Java | ["5 7 2\n3 1 3 2\n4 4 4 5", "5 4 2\n1 2 2 2\n4 3 4 4", "23 42 0"] | 2 seconds | ["8", "1", "102848351"] | NoteIn the first example, the initial grid looks like this:Here are $$$8$$$ ways to place zero or more extra dominoes to keep the placement perfectly balanced:In the second example, the initial grid looks like this:No extra dominoes can be placed here. | Java 8 | standard input | [
"dp",
"combinatorics"
] | 76fc2b718342821ac9d5a132a03c925e | The first line contains three integers $$$h$$$, $$$w$$$, and $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$), denoting the dimensions of the grid and the number of already placed dominoes. The rows are numbered from $$$1$$$ to $$$h$$$, and the columns are numbered from $$$1$$$ to $$$w$$$. Each of the next $$$n$$$ lines contains four integers $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$), denoting the row id and the column id of the cells covered by the $$$i$$$-th domino. Cells $$$(r_{i, 1}, c_{i, 1})$$$ and $$$(r_{i, 2}, c_{i, 2})$$$ are distinct and share a common side. The given domino placement is perfectly balanced. | 2,600 | Output the number of ways to place zero or more extra dominoes on the grid to keep the placement perfectly balanced, modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 5a29f895d5aa30896017d39886bd4928 | train_001.jsonl | 1571236500 | Consider a square grid with $$$h$$$ rows and $$$w$$$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $$$998\,244\,353$$$. | 512 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF1237F extends PrintWriter {
CF1237F() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1237F o = new CF1237F(); o.main(); o.flush();
}
static final int MD = 998244353;
int[] solve(boolean[] aa, int n, int k) {
int[] dp1 = new int[k + 1];
int[] dp2 = new int[k + 1];
int[] dp = new int[k + 1];
dp2[0] = dp1[0] = 1;
for (int i = 1; i < n; i++) {
dp[0] = 1;
for (int j = 1; j <= k; j++)
dp[j] = !aa[i - 1] && !aa[i] ? (dp2[j - 1] + dp1[j]) % MD : dp1[j];
int[] tmp = dp2; dp2 = dp1; dp1 = dp; dp = tmp;
}
return dp1;
}
int d_, x_, y_;
void gcd_(int a, int b) {
if (b == 0) {
d_ = a;
x_ = 1; y_ = 0;
} else {
gcd_(b, a % b);
int t = x_ - a / b * y_; x_ = y_; y_ = t;
}
}
int inv(int a) {
gcd_(a, MD);
return x_;
}
int[] ff, gg;
void init(int n) {
ff = new int[n + 1];
gg = new int[n + 1];
long f = 1;
for (int i = 0; i <= n; i++) {
gg[i] = inv(ff[i] = (int) f);
f = f * (i + 1) % MD;
}
}
long ch(int n, int k) {
return (long) ff[n] * gg[k] % MD * gg[n - k] % MD;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
boolean[] aa = new boolean[n];
boolean[] bb = new boolean[m];
while (k-- > 0) {
int i1 = sc.nextInt() - 1;
int j1 = sc.nextInt() - 1;
int i2 = sc.nextInt() - 1;
int j2 = sc.nextInt() - 1;
aa[i1] = aa[i2] = true;
bb[j1] = bb[j2] = true;
}
int n_ = n;
for (int i = 0; i < n; i++)
if (aa[i])
n_--;
int m_ = m;
for (int j = 0; j < m; j++)
if (bb[j])
m_--;
int[] da = solve(aa, n, n_ / 2);
int[] db = solve(bb, m, m_ / 2);
init(Math.max(n_, m_));
long ans = 0;
for (int k2 = 0; k2 * 2 <= n_; k2++) {
int x = da[k2];
if (x == 0)
continue;
for (int k1 = 0; k1 * 2 + k2 <= m_ && k2 * 2 + k1 <= n_; k1++) {
int y = db[k1];
if (y == 0)
continue;
long cnt = (long) x * y % MD * ch(n_ - k2 * 2, k1) % MD * ch(m_ - k1 * 2, k2) % MD * ff[k2] % MD * ff[k1] % MD;
ans += cnt;
}
}
ans %= MD;
if (ans < 0)
ans += MD;
println(ans);
}
}
| Java | ["5 7 2\n3 1 3 2\n4 4 4 5", "5 4 2\n1 2 2 2\n4 3 4 4", "23 42 0"] | 2 seconds | ["8", "1", "102848351"] | NoteIn the first example, the initial grid looks like this:Here are $$$8$$$ ways to place zero or more extra dominoes to keep the placement perfectly balanced:In the second example, the initial grid looks like this:No extra dominoes can be placed here. | Java 8 | standard input | [
"dp",
"combinatorics"
] | 76fc2b718342821ac9d5a132a03c925e | The first line contains three integers $$$h$$$, $$$w$$$, and $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$), denoting the dimensions of the grid and the number of already placed dominoes. The rows are numbered from $$$1$$$ to $$$h$$$, and the columns are numbered from $$$1$$$ to $$$w$$$. Each of the next $$$n$$$ lines contains four integers $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$), denoting the row id and the column id of the cells covered by the $$$i$$$-th domino. Cells $$$(r_{i, 1}, c_{i, 1})$$$ and $$$(r_{i, 2}, c_{i, 2})$$$ are distinct and share a common side. The given domino placement is perfectly balanced. | 2,600 | Output the number of ways to place zero or more extra dominoes on the grid to keep the placement perfectly balanced, modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 35cdb7a296b42accde745befa0980b27 | train_001.jsonl | 1571236500 | Consider a square grid with $$$h$$$ rows and $$$w$$$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $$$998\,244\,353$$$. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int h = in.readInt();
int w = in.readInt();
int n = in.readInt();
int[] r = new int[2 * n];
int[] c = new int[2 * n];
in.readIntArrays(r, c);
MiscUtils.decreaseByOne(r, c);
ArrayUtils.sort(r);
r = ArrayUtils.unique(r);
ArrayUtils.sort(c);
c = ArrayUtils.unique(c);
long[] horizontal = go(c, w);
long[] vertical = go(r, h);
long[] fact = IntegerUtils.generateFactorial(Math.max(h, w) + 1, MiscUtils.MODF);
long[] rev = IntegerUtils.generateReverseFactorials(Math.max(h, w) + 1, MiscUtils.MODF);
long answer = 0;
for (int i = 0; i < horizontal.length; i++) {
for (int j = 0; j < vertical.length; j++) {
if (2 * i + j <= w - c.length && 2 * j + i <= h - r.length) {
answer += horizontal[i] * vertical[j] % MiscUtils.MODF * fact[h - r.length - 2 * j] %
MiscUtils.MODF * rev[h - r.length - 2 * j - i] % MiscUtils.MODF
* fact[w - c.length - 2 * i] % MiscUtils.MODF * rev[w - c.length - 2 * i - j] %
MiscUtils.MODF;
}
}
}
out.printLine(answer % MiscUtils.MODF);
}
private long[] go(int[] c, int w) {
long[] result = new long[(w - c.length) / 2 + 1];
long[] next = new long[result.length];
long[] last = new long[result.length];
result[0] = 1;
int at = c.length - 1;
int col = w;
for (int i = w - 1; i >= 0; i--) {
System.arraycopy(result, 0, next, 0, result.length);
if (at >= 0 && c[at] == i) {
col = i;
at--;
}
if (col >= i + 2) {
for (int j = 1; j < result.length; j++) {
next[j] += last[j - 1];
if (next[j] >= MiscUtils.MODF) {
next[j] -= MiscUtils.MODF;
}
}
}
long[] temp = last;
last = result;
result = next;
next = temp;
}
return result;
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int index, int value) {
data[index] = value;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class ArrayUtils {
public static int[] sort(int[] array) {
return sort(array, IntComparator.DEFAULT);
}
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to, IntComparator comparator) {
if (from == 0 && to == array.length) {
new IntArray(array).sort(comparator);
} else {
new IntArray(array).subList(from, to).sort(comparator);
}
return array;
}
public static int[] unique(int[] array) {
return new IntArray(array).unique().toArray();
}
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static interface IntReversableCollection extends IntCollection {
}
static interface IntCollection extends IntStream {
public int size();
default public void add(int value) {
throw new UnsupportedOperationException();
}
default public int[] toArray() {
int size = size();
int[] array = new int[size];
int i = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
array[i++] = it.value();
}
return array;
}
default public IntCollection addAll(IntStream values) {
for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
add(it.value());
}
return this;
}
}
static interface IntComparator {
public static final IntComparator DEFAULT = (first, second) -> {
if (first < second) {
return -1;
}
if (first > second) {
return 1;
}
return 0;
};
public int compare(int first, int second);
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void set(int index, int value);
public abstract void addAt(int index, int value);
public abstract void removeAt(int index);
default public void swap(int first, int second) {
if (first == second) {
return;
}
int temp = get(first);
set(first, get(second));
set(second, temp);
}
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void add(int value) {
addAt(size(), value);
}
default public IntList sort(IntComparator comparator) {
Sorter.sort(this, comparator);
return this;
}
default IntList unique() {
int last = Integer.MIN_VALUE;
IntList result = new IntArrayList();
int size = size();
for (int i = 0; i < size; i++) {
int current = get(i);
if (current != last) {
result.add(current);
last = current;
}
}
return result;
}
default public IntList subList(final int from, final int to) {
return new IntList() {
private final int shift;
private final int size;
{
if (from < 0 || from > to || to > IntList.this.size()) {
throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size());
}
shift = from;
size = to - from;
}
public int size() {
return size;
}
public int get(int at) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
return IntList.this.get(at + shift);
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int at, int value) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
IntList.this.set(at + shift, value);
}
public IntList compute() {
return new IntArrayList(this);
}
};
}
}
static class Sorter {
private static final int INSERTION_THRESHOLD = 16;
private Sorter() {
}
public static void sort(IntList list, IntComparator comparator) {
quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1,
comparator);
}
private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) {
if (to - from < INSERTION_THRESHOLD) {
insertionSort(list, from, to, comparator);
return;
}
if (remaining == 0) {
heapSort(list, from, to, comparator);
return;
}
remaining--;
int pivotIndex = (from + to) >> 1;
int pivot = list.get(pivotIndex);
list.swap(pivotIndex, to);
int storeIndex = from;
int equalIndex = to;
for (int i = from; i < equalIndex; i++) {
int value = comparator.compare(list.get(i), pivot);
if (value < 0) {
list.swap(storeIndex++, i);
} else if (value == 0) {
list.swap(--equalIndex, i--);
}
}
quickSort(list, from, storeIndex - 1, remaining, comparator);
for (int i = equalIndex; i <= to; i++) {
list.swap(storeIndex++, i);
}
quickSort(list, storeIndex, to, remaining, comparator);
}
private static void heapSort(IntList list, int from, int to, IntComparator comparator) {
for (int i = (to + from - 1) >> 1; i >= from; i--) {
siftDown(list, i, to, comparator, from);
}
for (int i = to; i > from; i--) {
list.swap(from, i);
siftDown(list, from, i - 1, comparator, from);
}
}
private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) {
int value = list.get(start);
while (true) {
int child = ((start - delta) << 1) + 1 + delta;
if (child > end) {
return;
}
int childValue = list.get(child);
if (child + 1 <= end) {
int otherValue = list.get(child + 1);
if (comparator.compare(otherValue, childValue) > 0) {
child++;
childValue = otherValue;
}
}
if (comparator.compare(value, childValue) >= 0) {
return;
}
list.swap(start, child);
start = child;
}
}
private static void insertionSort(IntList list, int from, int to, IntComparator comparator) {
for (int i = from + 1; i <= to; i++) {
int value = list.get(i);
for (int j = i - 1; j >= from; j--) {
if (comparator.compare(list.get(j), value) <= 0) {
break;
}
list.swap(j, j + 1);
}
}
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
static class IntArrayList extends IntAbstractStream implements IntList {
private int size;
private int[] data;
public IntArrayList() {
this(3);
}
public IntArrayList(int capacity) {
data = new int[capacity];
}
public IntArrayList(IntCollection c) {
this(c.size());
addAll(c);
}
public IntArrayList(IntStream c) {
this();
if (c instanceof IntCollection) {
ensureCapacity(((IntCollection) c).size());
}
addAll(c);
}
public IntArrayList(IntArrayList c) {
size = c.size();
data = c.data.clone();
}
public IntArrayList(int[] arr) {
size = arr.length;
data = arr.clone();
}
public int size() {
return size;
}
public int get(int at) {
if (at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size);
}
return data[at];
}
private void ensureCapacity(int capacity) {
if (data.length >= capacity) {
return;
}
capacity = Math.max(2 * data.length, capacity);
data = Arrays.copyOf(data, capacity);
}
public void addAt(int index, int value) {
ensureCapacity(size + 1);
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size) {
System.arraycopy(data, index, data, index + 1, size - index);
}
data[index] = value;
size++;
}
public void removeAt(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size - 1) {
System.arraycopy(data, index + 1, data, index, size - index - 1);
}
size--;
}
public void set(int index, int value) {
if (index >= size) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
data[index] = value;
}
public int[] toArray() {
return Arrays.copyOf(data, size);
}
}
static class IntegerUtils {
public static long[] generateFactorial(int count, long module) {
long[] result = new long[count];
if (module == -1) {
if (count != 0) {
result[0] = 1;
}
for (int i = 1; i < count; i++) {
result[i] = result[i - 1] * i;
}
} else {
if (count != 0) {
result[0] = 1 % module;
}
for (int i = 1; i < count; i++) {
result[i] = (result[i - 1] * i) % module;
}
}
return result;
}
public static long[] generateReverse(int upTo, long module) {
long[] result = new long[upTo];
if (upTo > 1) {
result[1] = 1;
}
for (int i = 2; i < upTo; i++) {
result[i] = (module - module / i * result[((int) (module % i))] % module) % module;
}
return result;
}
public static long[] generateReverseFactorials(int upTo, long module) {
long[] result = generateReverse(upTo, module);
if (upTo > 0) {
result[0] = 1;
}
for (int i = 1; i < upTo; i++) {
result[i] = result[i] * result[i - 1] % module;
}
return result;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class MiscUtils {
public static final int MODF = 998_244_353;
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++) {
array[i]--;
}
}
}
}
}
| Java | ["5 7 2\n3 1 3 2\n4 4 4 5", "5 4 2\n1 2 2 2\n4 3 4 4", "23 42 0"] | 2 seconds | ["8", "1", "102848351"] | NoteIn the first example, the initial grid looks like this:Here are $$$8$$$ ways to place zero or more extra dominoes to keep the placement perfectly balanced:In the second example, the initial grid looks like this:No extra dominoes can be placed here. | Java 8 | standard input | [
"dp",
"combinatorics"
] | 76fc2b718342821ac9d5a132a03c925e | The first line contains three integers $$$h$$$, $$$w$$$, and $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$), denoting the dimensions of the grid and the number of already placed dominoes. The rows are numbered from $$$1$$$ to $$$h$$$, and the columns are numbered from $$$1$$$ to $$$w$$$. Each of the next $$$n$$$ lines contains four integers $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$), denoting the row id and the column id of the cells covered by the $$$i$$$-th domino. Cells $$$(r_{i, 1}, c_{i, 1})$$$ and $$$(r_{i, 2}, c_{i, 2})$$$ are distinct and share a common side. The given domino placement is perfectly balanced. | 2,600 | Output the number of ways to place zero or more extra dominoes on the grid to keep the placement perfectly balanced, modulo $$$998\,244\,353$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.