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 | f648a41f8104de2ceb77d63dd4df63e2 | train_003.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.Scanner;
public class ahmed {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int k = input.nextInt();
int count = 0;
int y = 0;
int[][] arr = new int[n][2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = input.nextInt();
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
}
count += arr[i][1] - (arr[i][0]-1);
}
while (true){
if (count % k == 0){
System.out.println(y);
break;
}else {
count++;
y++;
if (count % k ==0){
System.out.println(y);
break;
}
}
}
}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 11 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 02145ea484caf064f91a3c96356e8d84 | train_003.jsonl | 1311346800 | A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (l ≥ w) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him... | 256 megabytes | import java.util.Scanner;
public class Codeforces98C {
static double x, y, l;
static double EPS = 1e-7;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
y = in.nextDouble();
x = in.nextDouble();
l = in.nextDouble();
solve();
}
static void solve(){
if (l<=x){
System.out.println(Math.min(y, l));
return;
}
if (l<=y){
System.out.println(Math.min(x, l));
return;
}
double a = 0, b = l;
double m1, m2;
for (int i = 0; i < 500; i++) {
m1 = (b-a)/3 + a;
m2 = 2*(b-a)/3 + a;
double c = f(m1);
double d = f(m2);
if (c>d) a = m1;
else b = m2;
}
if (f(a) < EPS) System.out.println("My poor head =(");
else System.out.println(f(a));
}
static double f(double d){
double h = Math.sqrt(l*l-d*d);
return distPS(new double[]{0, h}, new double[]{d, 0}, new double[]{x, y});
}
//Geom primitives
static double ds(double[] a, double[] b) {return (b[0]-a[0])*(b[0]-a[0])+(b[1]-a[1])*(b[1]-a[1]);}
static double distPL(double[] p1, double[] p2, double[] p) {
return Math.abs((p2[0]-p1[0])*(p1[1]-p[1])-(p2[1]-p1[1])*(p1[0]-p[0]))/Math.sqrt(ds(p1,p2));
}
static double distPS(double[] p1, double[] p2, double[] p) {
double dP=ds(p1,p2),d1=ds(p1,p),d2=ds(p2,p);
return (d2+dP<d1||d1+dP<d2)?Math.sqrt(Math.min(d1,d2)):distPL(p1,p2,p);
}
}
| Java | ["2 2 1", "2 2 2", "2 2 3", "2 2 6"] | 2 seconds | ["1.0000000", "2.0000000", "1.3284271", "My poor head =("] | NoteIn the first example the answer is restricted by the coffin's length (remember — coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember — arbitrary moves and rotations of the coffin are possible). | Java 8 | standard input | [
"geometry",
"ternary search"
] | c4b0f9263e18aac26124829cf3d880b6 | The first line contains three space-separated integers a, b and l from the problem's statement (1 ≤ a, b, l ≤ 104). | 2,500 | Print the maximally possible width of a coffin with absolute or relative error no more than 10 - 7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes). It is guaranteed that if the answer is positive, it will be not less than 10 - 7. All the hacks will also be checked to meet that condition. | standard output | |
PASSED | 45979c971ac9752fcf723d9a731fec60 | train_003.jsonl | 1311346800 | A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (l ≥ w) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him... | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Help_Greg_Dwarf_CD98C {
static double a ;
static double b ;
static double l;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out= new PrintWriter(System.out);
String linea =in.readLine();
while(linea!=null&&!linea.trim().equals("")){
StringTokenizer toks= new StringTokenizer(linea);
a=Integer.parseInt(toks.nextToken());
b=Integer.parseInt(toks.nextToken());
l =Integer.parseInt(toks.nextToken());
double k=solve();
String res=String.format("%.7f", disPS(0,Math.sqrt(Math.pow(l, 2)-Math.pow(k, 2)),k,0,b,a)).replace(",", ".");
if(l<=a&&b>=l)
out.println(String.format("%.7f", l).replace(",", "."));
else if(l<=a&&l>b)
out.println(String.format("%.7f", b).replace(",", "."));
else if(l<=b&&a<l)
out.println(String.format("%.7f", a).replace(",", "."));
else if(res.equals("0.0000000"))
out.println("My poor head =(");
else
out.println(res);
linea=in.readLine();
}
out.close();
}
static double solve(){
double left=0;
double right=l;
int i =0;
double t1;
double t2;
while(i++<600){
t1= ((right - left ) / 3) + left;
t2 = 2*(right - left)/3 + left;
t1= ((right - left ) / 3) + left;
t2 = 2*(right - left)/3 + left;
double x=Math.pow(l, 2);
double y=Math.pow(t2, 2);
double z=Math.pow(t1, 2);
double k1 =disPS(0,Math.sqrt(x-z),t1,0,b,a);
double k2=disPS(0,Math.sqrt(x-y),t2,0,b,a);
if (k1<k2)
right=t2;
else
left=t1;
}
return (left+right)/2;
}
static double dis(double x,double y,double x1,double y1){
return (x1-x)*(x1-x)+(y1-y)*(y1-y);
}
static double distPL(double x,double y,double x1,double y1,double x2,double y2){
return Math.abs((x1-x)*(y-y2)-(y1-y)*(x-x2))/Math.sqrt(dis(x,y,x1,y1));
}
static double disPS(double x,double y,double x1,double y1,double x2,double y2){
double dP=dis(x,y,x1,y1),d1=dis(x,y,x2,y2),d2=dis(x1,y1,x2,y2);
return (d2+dP<d1||d1+dP<d2)?Math.sqrt(Math.min(d1, d2)):distPL(x,y,x1,y1,x2,y2);
}
}
| Java | ["2 2 1", "2 2 2", "2 2 3", "2 2 6"] | 2 seconds | ["1.0000000", "2.0000000", "1.3284271", "My poor head =("] | NoteIn the first example the answer is restricted by the coffin's length (remember — coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember — arbitrary moves and rotations of the coffin are possible). | Java 8 | standard input | [
"geometry",
"ternary search"
] | c4b0f9263e18aac26124829cf3d880b6 | The first line contains three space-separated integers a, b and l from the problem's statement (1 ≤ a, b, l ≤ 104). | 2,500 | Print the maximally possible width of a coffin with absolute or relative error no more than 10 - 7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes). It is guaranteed that if the answer is positive, it will be not less than 10 - 7. All the hacks will also be checked to meet that condition. | standard output | |
PASSED | 5e8be0f44b4407295f4290b78d775f69 | train_003.jsonl | 1311346800 | A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (l ≥ w) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him... | 256 megabytes | //package round78;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
Scanner in;
PrintWriter out;
String INPUT = "2 1 2";
void solve()
{
double a = ni();
double b = ni();
double l = ni();
if(!check(a, b, 0, l)){
out.println("My poor head =(");
return;
}
double inf = 0;
double sup = Math.min(a, Math.min(b, l));
if(l <= b){
inf = Math.min(a,sup);
}
if(l <= a){
inf = Math.min(b,sup);
}
while(sup - inf > 1E-9){
double w = (sup+inf)/2;
if(check(a, b, w, l)){
inf = w;
}else{
sup = w;
}
}
out.printf("%.7f\n", inf);
}
boolean check(double a, double b, double w, double l)
{
return GSM(1E-9, Math.PI/2-1E-9, a, b, w) >= l;
}
public double GSM(double inf, double sup, double a, double b, double w)
{
double tau = (Math.sqrt(5)-1)/2;
double m1 = inf, m2 = sup;
double dm1 = Double.NaN, dm2 = Double.NaN;
while(sup - inf > 1E-9){
if(Double.isNaN(dm1)){
m1 = sup + tau * (inf - sup);
dm1 = f(m1, a, b, w);
}
if(Double.isNaN(dm2)){
m2 = inf + tau * (sup - inf);
dm2 = f(m2, a, b, w);
}
if(dm1 < dm2){
sup = m2;
dm2 = dm1;
m2 = m1;
dm1 = Double.NaN;
}else{
inf = m1;
dm1 = dm2;
m1 = m2;
dm2 = Double.NaN;
}
}
return f(inf, a, b, w);
}
static double f(double x, double a, double b, double w)
{
return (a-w*Math.cos(x)) / Math.sin(x) + (b-w*Math.sin(x)) / Math.cos(x);
}
void run() throws Exception
{
in = oj ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{
new C().run();
}
int ni() { return Integer.parseInt(in.next()); }
long nl() { return Long.parseLong(in.next()); }
double nd() { return Double.parseDouble(in.next()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["2 2 1", "2 2 2", "2 2 3", "2 2 6"] | 2 seconds | ["1.0000000", "2.0000000", "1.3284271", "My poor head =("] | NoteIn the first example the answer is restricted by the coffin's length (remember — coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember — arbitrary moves and rotations of the coffin are possible). | Java 6 | standard input | [
"geometry",
"ternary search"
] | c4b0f9263e18aac26124829cf3d880b6 | The first line contains three space-separated integers a, b and l from the problem's statement (1 ≤ a, b, l ≤ 104). | 2,500 | Print the maximally possible width of a coffin with absolute or relative error no more than 10 - 7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes). It is guaranteed that if the answer is positive, it will be not less than 10 - 7. All the hacks will also be checked to meet that condition. | standard output | |
PASSED | 859ac3e583205204cc3af9795fc2c9e4 | train_003.jsonl | 1311346800 | A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (l ≥ w) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him... | 256 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class Main {
private static final int MAX = 1000;
private static final double eps = 1e-9;
private static double a;
private static double b;
private static double c;
public static void main(String[] args) throws IOException {
InputStream fin = System.in;
// fin = new FileInputStream("in.txt");
Scanner cin = new Scanner(fin);
while (cin.hasNext()) {
a = cin.nextDouble();
b = cin.nextDouble();
c = cin.nextDouble();
double l = 0.0, r = Math.PI / 2.0, ret = c;
for (int i = 0; i < MAX; i++) {
double mid1 = l + (r - l) / 3.0;
double mid2 = l + 2 * (r - l) / 3.0;
double ll = F(mid1);
double rr = F(mid2);
if (ll > rr)
l = mid1;
else
r = mid2;
}
ret = Math.min(c, F(l));
if (sgn(b - c) >= 0)
ret = Math.max(ret, Math.min(a, c));
if (sgn(a - c) >= 0)
ret = Math.max(ret, Math.min(b, c));
if (sgn(ret) <= 0)
System.out.println("My poor head =(");
else
System.out.printf("%.15f\n", ret);
}
fin.close();
cin.close();
}
private static int sgn(double d) {
return d < -eps ? -1 : d > eps ? 1 : 0;
}
private static double F(double t) {
return b * Math.cos(t) + a * Math.sin(t) - c * Math.sin(t)
* Math.cos(t);
}
} | Java | ["2 2 1", "2 2 2", "2 2 3", "2 2 6"] | 2 seconds | ["1.0000000", "2.0000000", "1.3284271", "My poor head =("] | NoteIn the first example the answer is restricted by the coffin's length (remember — coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember — arbitrary moves and rotations of the coffin are possible). | Java 6 | standard input | [
"geometry",
"ternary search"
] | c4b0f9263e18aac26124829cf3d880b6 | The first line contains three space-separated integers a, b and l from the problem's statement (1 ≤ a, b, l ≤ 104). | 2,500 | Print the maximally possible width of a coffin with absolute or relative error no more than 10 - 7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes). It is guaranteed that if the answer is positive, it will be not less than 10 - 7. All the hacks will also be checked to meet that condition. | standard output | |
PASSED | fca91156524048915f3a6e7747b2d9bd | train_003.jsonl | 1311346800 | A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (l ≥ w) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him... | 256 megabytes |
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
/**
* @author Ivan Pryvalov (ivan.pryvalov@gmail.com)
*/
public class Codeforces78_Div2_ProblemE implements Runnable{
double A,B,L;
double EPS = 1e-10;
private void solve() throws IOException {
A = scanner.nextInt();
B = scanner.nextInt();
L = scanner.nextInt();
double w = 0;
if (B-L > -EPS || A-L > -EPS){
w = Math.min(L, Math.min(A, B));
out.println(w);
return;
}
if (!check(w)){
out.println("My poor head =(");
}else{
double w2 = 1e-8;
while (check(w2)){
w2 *= 2;
}
double w1 = w2/2.0;
w = binarySearch(w1,w2);
out.println(w);
}
}
private double binarySearch(double w1, double w2) {
while (Math.abs(w2-w1)>EPS){
double w = (w1+w2)/2.0;
if (check(w)){
w1 = w;
}else{
w2 = w;
}
}
return (w1+w2)/2.0;
}
private boolean check(double w) {
double minL = binarySearchMinL(w, 0, Math.PI/2);
return minL - L > -EPS && L-w > -EPS;
}
private double binarySearchMinL(double w, double l, double r) {
while (Math.abs(l-r)>EPS){
double c = (l+r)/2.0;
double dc = 1e-8;
double fC = getL(c,w);
double fC2 = getL(c+dc,w);
if (fC2 > fC){
r = c;
}else{
l = c;
}
}
return getL(l, w);
}
public double getL(double a, double w){
return A/Math.cos(a) + B/Math.sin(a) - 2*w/Math.sin(2*a);
}
/////////////////////////////////////////////////
final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly
final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ;
final int BUF_SIZE_INPUT = 1024;
final int BUF_SIZE_OUT = 1024;
boolean inputFromFile = false;
String filenamePrefix = "A-small-attempt0";
String inSuffix = ".in";
String outSuffix = ".out";
//InputStream bis;
//OutputStream bos;
PrintStream out;
ByteScanner scanner;
ByteWriter writer;
@Override
public void run() {
try{
InputStream bis = null;
OutputStream bos = null;
//PrintStream out = null;
if (inputFromFile){
File baseFile = new File(getClass().getResource("/").getFile());
bis = new BufferedInputStream(
new FileInputStream(new File(
baseFile, filenamePrefix+inSuffix)),
INPUT_BUFFER_SIZE);
bos = new BufferedOutputStream(
new FileOutputStream(
new File(baseFile, filenamePrefix+outSuffix)));
out = new PrintStream(bos);
}else{
bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE);
bos = new BufferedOutputStream(System.out);
out = new PrintStream(bos);
}
scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE);
writer = new ByteWriter(bos, BUF_SIZE_OUT);
solve();
out.flush();
}catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public interface Constants{
final static byte ZERO = '0';//48 or 0x30
final static byte NINE = '9';
final static byte SPACEBAR = ' '; //32 or 0x20
final static byte MINUS = '-'; //45 or 0x2d
final static char FLOAT_POINT = '.';
}
public static class EofException extends IOException{
}
public static class ByteWriter implements Constants {
int bufSize = -1;//1024;
byte[] byteBuf = null;//new byte[bufSize];
OutputStream os;
public ByteWriter(OutputStream os, int bufSize){
this.os = os;
this.bufSize = bufSize;
byteBuf = new byte[bufSize];
}
public void writeInt(int num) throws IOException{
int byteWriteOffset = byteBuf.length;
if (num==0){
byteBuf[--byteWriteOffset] = ZERO;
}else{
int numAbs = Math.abs(num);
while (numAbs>0){
byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO);
numAbs /= 10;
}
if (num<0) byteBuf[--byteWriteOffset] = MINUS;
}
os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset);
}
public void writeLong(long num) throws IOException{
int byteWriteOffset = byteBuf.length;
if (num==0){
byteBuf[--byteWriteOffset] = ZERO;
}else{
long numAbs = Math.abs(num);
while (numAbs>0){
byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO);
numAbs /= 10;
}
if (num<0) byteBuf[--byteWriteOffset] = MINUS;
}
os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset);
}
/* No need
public void writeDouble(double num) throws IOException{
byte[] data = Double.toString(num).getBytes();
os.write(data,0,data.length);
}*/
//NO NEED: Please ensure ar.length <= byteBuf.length!
/**
*
* @param ar
* @throws IOException
*/
public void writeByteAr(byte[] ar) throws IOException{
/*
for (int i = 0; i < ar.length; i++) {
byteBuf[i] = ar[i];
}
os.write(byteBuf,0,ar.length);*/
os.write(ar,0,ar.length);
}
public void writeSpaceBar() throws IOException{
os.write(SPACEBAR);
}
}
public static class ByteScanner implements Constants{
InputStream is;
public ByteScanner(InputStream is, int bufSizeInput, int bufSize){
this.is = is;
this.bufSizeInput = bufSizeInput;
this.bufSize = bufSize;
byteBufInput = new byte[this.bufSizeInput];
byteBuf = new byte[this.bufSize];
}
public ByteScanner(byte[] data){
byteBufInput = data;
bufSizeInput = data.length;
bufSize = data.length;
byteBuf = new byte[bufSize];
byteRead = data.length;
bytePos = 0;
}
private int bufSizeInput;
private int bufSize;
byte[] byteBufInput;
byte by=-1;
int byteRead=-1;
int bytePos=-1;
static byte[] byteBuf;
int totalBytes;
boolean eofMet = false;
private byte nextByte() throws IOException{
if (bytePos<0 || bytePos>=byteRead){
byteRead = is==null? -1: is.read(byteBufInput);
bytePos=0;
if (byteRead<0){
byteBufInput[bytePos]=-1;//!!!
if (eofMet)
throw new EofException();
eofMet = true;
}
}
return byteBufInput[bytePos++];
}
/**
* Returns next meaningful character as a byte.<br>
*
* @return
* @throws IOException
*/
public byte nextChar() throws IOException{
while ((by=nextByte())<=0x20);
return by;
}
/**
* Returns next meaningful character OR space as a byte.<br>
*
* @return
* @throws IOException
*/
public byte nextCharOrSpacebar() throws IOException{
while ((by=nextByte())<0x20);
return by;
}
/**
* Reads line.
*
* @return
* @throws IOException
*/
public String nextLine() throws IOException {
readToken((byte)0x20);
return new String(byteBuf,0,totalBytes);
}
public byte[] nextLineAsArray() throws IOException {
readToken((byte)0x20);
byte[] out = new byte[totalBytes];
System.arraycopy(byteBuf, 0, out, 0, totalBytes);
return out;
}
/**
* Reads token. Spacebar is separator char.
*
* @return
* @throws IOException
*/
public String nextToken() throws IOException {
readToken((byte)0x21);
return new String(byteBuf,0,totalBytes);
}
/**
* Spacebar is included as separator char
*
* @throws IOException
*/
private void readToken() throws IOException {
readToken((byte)0x21);
}
private void readToken(byte acceptFrom) throws IOException {
totalBytes = 0;
while ((by=nextByte())<acceptFrom);
byteBuf[totalBytes++] = by;
while ((by=nextByte())>=acceptFrom){
byteBuf[totalBytes++] = by;
}
}
public int nextInt() throws IOException{
readToken();
int num=0, i=0;
boolean sign=false;
if (byteBuf[i]==MINUS){
sign = true;
i++;
}
for (; i<totalBytes; i++){
num*=10;
num+=byteBuf[i]-ZERO;
}
return sign?-num:num;
}
public long nextLong() throws IOException{
readToken();
long num=0;
int i=0;
boolean sign=false;
if (byteBuf[i]==MINUS){
sign = true;
i++;
}
for (; i<totalBytes; i++){
num*=10;
num+=byteBuf[i]-ZERO;
}
return sign?-num:num;
}
/*
//TODO test Unix/Windows formats
public void toNextLine() throws IOException{
while ((ch=nextChar())!='\n');
}
*/
public double nextDouble() throws IOException{
readToken();
char[] token = new char[totalBytes];
for (int i = 0; i < totalBytes; i++) {
token[i] = (char)byteBuf[i];
}
return Double.parseDouble(new String(token));
}
}
public static void main(String[] args) {
new Codeforces78_Div2_ProblemE().run();
}
}
| Java | ["2 2 1", "2 2 2", "2 2 3", "2 2 6"] | 2 seconds | ["1.0000000", "2.0000000", "1.3284271", "My poor head =("] | NoteIn the first example the answer is restricted by the coffin's length (remember — coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember — arbitrary moves and rotations of the coffin are possible). | Java 6 | standard input | [
"geometry",
"ternary search"
] | c4b0f9263e18aac26124829cf3d880b6 | The first line contains three space-separated integers a, b and l from the problem's statement (1 ≤ a, b, l ≤ 104). | 2,500 | Print the maximally possible width of a coffin with absolute or relative error no more than 10 - 7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes). It is guaranteed that if the answer is positive, it will be not less than 10 - 7. All the hacks will also be checked to meet that condition. | standard output | |
PASSED | 8e9eb04058d298b1098334ae1b277b0d | train_003.jsonl | 1311346800 | A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (l ≥ w) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him... | 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.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class Coffin implements Runnable {
private void solve() throws IOException {
int a = nextInt();
int b = nextInt();
int l = nextInt();
if (l <= a || l <= b) {
writer.println(Math.min(l, Math.min(a, b)));
return;
}
double[] koef = new double[5];
koef[4] = -a - l;
koef[3] = -2 * b;
koef[2] = 6 * l;
koef[1] = -2 * b;
koef[0] = a - l;
List<Double> zeroes = findZeroes(koef);
zeroes.add(0.0);
zeroes.add(1.0);
double res = l;
for (double u : zeroes) {
double cur = b * (1 - u * u) / (1 + u * u) + a * 2 * u / (1 + u * u) - l * 2 * u * (1 - u * u) / (1 + u * u) / (1 + u * u);
res = Math.min(res, cur);
}
if (res < 0.5e-7) {
writer.println("My poor head =(");
} else {
writer.println(res);
}
}
private double eval(double[] koef, double x) {
double res = 0.0;
for (int i = koef.length - 1; i >= 0; --i) {
res = res * x + koef[i];
}
return res;
}
private List<Double> findZeroes(double[] koef) {
List<Double> res = new ArrayList<Double>();
if (koef.length == 3) {
double a = koef[2];
double b = koef[1];
double c = koef[0];
double d = b * b - 4 * a * c;
if (d < 0) {
return res;
}
d = Math.sqrt(d);
double sol = (-b + d) / (2 * a);
if (sol > 0.0 && sol < 1.0) res.add(sol);
sol = (-b - d) / (2 * a);
if (sol > 0.0 && sol < 1.0) res.add(sol);
Collections.sort(res);
return res;
}
double[] deriv = new double[koef.length - 1];
for (int i = 1; i < koef.length; ++i)
deriv[i - 1] = i * koef[i];
List<Double> derivZeroes = findZeroes(deriv);
derivZeroes.add(0.0);
derivZeroes.add(1.0);
Collections.sort(derivZeroes);
double[] val = new double[derivZeroes.size()];
for (int i = 0; i < derivZeroes.size(); ++i) {
double x = derivZeroes.get(i);
val[i] = eval(koef, x);
if (val[i] == 0) res.add(x);
}
for (int i = 0; i + 1 < val.length; ++i) {
if (val[i] * val[i + 1] < 0) {
double left = derivZeroes.get(i);
double right = derivZeroes.get(i + 1);
int j;
for (j = 0; j < 200; ++j) {
double middle = (left + right) / 2;
double v = eval(koef, middle);
if (v == 0) {
res.add(middle);
break;
}
if (v * val[i] < 0)
right = middle;
else
left = middle;
}
if (j == 200) {
res.add((left + right) / 2);
}
}
}
Collections.sort(res);
return res;
}
public static void main(String[] args) {
new Coffin().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["2 2 1", "2 2 2", "2 2 3", "2 2 6"] | 2 seconds | ["1.0000000", "2.0000000", "1.3284271", "My poor head =("] | NoteIn the first example the answer is restricted by the coffin's length (remember — coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember — arbitrary moves and rotations of the coffin are possible). | Java 6 | standard input | [
"geometry",
"ternary search"
] | c4b0f9263e18aac26124829cf3d880b6 | The first line contains three space-separated integers a, b and l from the problem's statement (1 ≤ a, b, l ≤ 104). | 2,500 | Print the maximally possible width of a coffin with absolute or relative error no more than 10 - 7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes). It is guaranteed that if the answer is positive, it will be not less than 10 - 7. All the hacks will also be checked to meet that condition. | standard output | |
PASSED | f63d41e02090c6452a76711cb6f6b350 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
private static final int MOD = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = Utils.readIntArray(in, n);
int[] dp = new int[1 << 20];
int[] next = new int[1 << 20];
for (int i = 0; i < n; ++i) {
dp[a[i]]++;
}
for (int k = 0; k < 20; ++k) {
for (int mask = 0; mask < (1 << 20); ++mask) {
next[mask] += dp[mask];
if (next[mask] >= MOD) next[mask] -= MOD;
if (!BitUtils.checkBit(mask, k)) {
next[mask] += dp[BitUtils.setBit(mask, k)];
if (next[mask] >= MOD) next[mask] -= MOD;
}
}
int[] temp = dp;
dp = next;
next = temp;
Arrays.fill(next, 0);
}
int res = IntegerUtils.pow(2, n, MOD) - 1;
if (res < 0) res += MOD;
for (int mask = 1; mask < (1 << 20); ++mask) {
int sign = 1;
if ((Integer.bitCount(mask) & 1) == 1) {
sign = -1;
}
res += sign * ((IntegerUtils.pow(2, dp[mask], MOD) - 1 + MOD) % MOD);
while (res < 0) res += MOD;
while (res >= MOD) res -= MOD;
}
out.println(res);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine().trim();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
class Utils {
public static int[] readIntArray(InputReader in, int n) {
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
}
return a;
}
}
class BitUtils {
public static boolean checkBit(int mask, int bit) {
return (mask & (1 << bit)) > 0;
}
public static int setBit(int mask, int bit) {
return (mask | (1 << bit));
}
}
class IntegerUtils {
public static int pow(int x, int p, int MOD) {
int result = 1;
for (int i = p; i > 0; i >>= 1) {
if ((i & 1) != 0) {
result = (int) ((result * 1L * x) % MOD);
}
x = (int) ((x * 1L * x) % MOD);
}
return result;
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | a49a003987fd3f2f07c4e819455eafe6 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
static final long MOD = (long) (1e9 + 7);
public static void main(String[] args) {
MyScanner in = new MyScanner();
int n = in.nextInt();
int[] supersets = new int[1 << 20];
for (int i = 0; i < n; i++)
supersets[in.nextInt()]++;
for (int i = 0; i < 20; i++) {
for (int mask = 0; mask < supersets.length; mask++) {
if (((1 << i) & mask) != 0) {
supersets[mask ^ (1 << i)] += supersets[mask];
}
}
}
long[] pow2 = new long[n + 1];
pow2[0] = 1;
for (int i = 1; i < n + 1; i++)
pow2[i] = (pow2[i - 1] * 2) % MOD;
long ans = 0;
for (int i = 0; i < supersets.length; i++) {
ans += pow2[supersets[i]] * (Integer.bitCount(i) % 2 == 0 ? 1 : -1);
ans = (ans + MOD) % MOD;
}
System.out.println(ans);
}
private static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 4bccc1494b97e7569d882c6e182842e9 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStreamReader;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
private static final int MAX_LENGTH = 20;
private static final int MODULO = 1000000007;
private int powMod(long x, int y) {
long res = 1;
for (; y != 0; y >>= 1) {
if (y % 2 == 1) {
res = res * x % MODULO;
}
x = x * x % MODULO;
}
return (int) res;
}
private void go(int[] a, int depth) {
if (a.length == 2) {
a[0] = (int) ((a[0] + a[1] * (long) a[0]) % MODULO);
return;
}
int[] u = new int[1 << (depth - 1)];
int[] v = new int[1 << (depth - 1)];
for (int i = 0; i < (1 << (depth - 1)); ++i) {
u[i] = a[i + (1 << (depth - 1))];
v[i] = (int) ((a[i] + u[i] + a[i] * (long) u[i]) % MODULO);
}
go(u, depth - 1);
go(v, depth - 1);
for (int i = 0; i < (1 << (depth - 1)); ++i) {
a[i] = (v[i] - u[i]) % MODULO;
a[i + (1 << (depth - 1))] = u[i];
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[1 << MAX_LENGTH];
for (int i = 0; i < n; ++i) {
++a[in.nextInt()];
}
for (int i = 0; i < (1 << MAX_LENGTH); ++i) {
a[i] = (powMod(2, a[i]) - 1) % MODULO;
}
go(a, MAX_LENGTH);
int answer = (a[0] + MODULO) % MODULO;
out.println(answer);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 663fe9b08280f11516bb6a21b8c2474c | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import static java.lang.Math.pow;
import java.math.BigInteger.*;
import static java.math.BigInteger.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.fill;
//<editor-fold defaultstate="collapsed" desc="Imports">
//</editor-fold>
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
//<editor-fold defaultstate="collapsed" desc="Main">
public class Main {
private void run() {
Locale.setDefault(Locale.US);
boolean oj = true;
try {
oj = System.getProperty("MYLOCAL") == null;
} catch (Exception e) {
}
if (oj) {
sc = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
} else {
try {
sc = new FastScanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
MLE();
}
}
Solver s = new Solver();
s.sc = sc;
s.out = out;
s.solve();
err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
out.flush();
}
private void show(int[] arr) {
for (int v : arr) {
err.print(" " + v);
}
err.println();
}
public static void MLE() {
// int[][] arr = new int[1024 * 1024][];
// for (int i = 0; i < arr.length; i++) {
// arr[i] = new int[1024 * 1024];
// }
System.exit(0);
}
public static void main(String[] args) {
new Main().run();
}
long timeBegin = System.currentTimeMillis();
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader reader) {
br = new BufferedReader(reader);
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ex) {
Main.MLE();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
//</editor-fold>
class Solver {
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
final int cntBits = 20, mod = (int)1e9 + 7;
int n;
int[] a;
int[] f = new int[1<<cntBits];
final int[] pow2 = new int[1<<cntBits];
{
pow2[0] = 1;
for (int i = 1; i < pow2.length; i++) {
pow2[i] = (pow2[i-1] * 2) % mod;
}
}
void solve(){
n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
++f[a[i]];
}
// bf();
for (int k = 1; k <= cntBits; k++) {
for (int msk = 0; msk < (1<<cntBits); msk++) {
if( (msk&(1<<(k-1))) == 0 )
f[msk] = (f[msk] + f[msk+(1<<(k-1))]) % mod;
}
}
// err.println(Arrays.toString(f[cntBits]));
long ans = 0;
for (int msk = 0; msk < (1<<cntBits); msk++) {
long cur = pow2[f[msk]];
if( Integer.bitCount(msk)%2==0 )
ans += cur;
else
ans -= cur;
}
ans = ( ans % mod + mod ) % mod;
out.println( ans );
}
// void bf() {
// int[] ffff = new int[1<<cntBits];
// for (int ai : a) {
// for (int x = 0; x < ffff.length; x++) {
// if ((ai & x) == x) {
// ++ffff[x];
// }
// }
// }
// err.println(Arrays.toString(ffff));
//
// double ans = 0;
// for (int x = 0; x < ffff.length; x++) {
// ans += pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]);
// out.printf("%4s %d %3.0f\n",
// Integer.toBinaryString(x),
// ffff[x],
// pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]));
// }
// out.println(ans);
// }
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 8171ca4119c8206d5242be6a75781dd5 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import static java.lang.Math.pow;
import java.math.BigInteger.*;
import static java.math.BigInteger.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.fill;
//<editor-fold defaultstate="collapsed" desc="Imports">
//</editor-fold>
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
//<editor-fold defaultstate="collapsed" desc="Main">
public class Main {
private void run() {
Locale.setDefault(Locale.US);
boolean oj = true;
try {
oj = System.getProperty("MYLOCAL") == null;
} catch (Exception e) {
}
if (oj) {
sc = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
} else {
try {
sc = new FastScanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
MLE();
}
}
Solver s = new Solver();
s.sc = sc;
s.out = out;
s.solve();
err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
out.flush();
}
private void show(int[] arr) {
for (int v : arr) {
err.print(" " + v);
}
err.println();
}
public static void MLE() {
// int[][] arr = new int[1024 * 1024][];
// for (int i = 0; i < arr.length; i++) {
// arr[i] = new int[1024 * 1024];
// }
System.exit(0);
}
public static void main(String[] args) {
new Main().run();
}
long timeBegin = System.currentTimeMillis();
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader reader) {
br = new BufferedReader(reader);
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ex) {
Main.MLE();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
//</editor-fold>
class Solver {
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
final int cntBits = 20, mod = (int)1e9 + 7;
int n;
int[] a;
int[] f = new int[1<<cntBits];
final int[] pow2 = new int[1<<cntBits];
{
pow2[0] = 1;
for (int i = 1; i < pow2.length; i++) {
pow2[i] = (pow2[i-1] + pow2[i-1]);
if( mod <= pow2[i] ) pow2[i] -= mod;
}
}
void solve(){
n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
++f[a[i]];
}
// bf();
for (int k = 1; k <= cntBits; k++) {
for (int msk = 0; msk < (1<<cntBits); msk++) {
if( (msk&(1<<(k-1))) == 0 ){
f[msk] = f[msk] + f[msk+(1<<(k-1))];
if( mod <= f[msk] ) f[msk] -= mod;
}
}
}
// err.println(Arrays.toString(f[cntBits]));
long ans = 0;
for (int msk = 0; msk < (1<<cntBits); msk++) {
long cur = pow2[f[msk]];
if( Integer.bitCount(msk)%2==0 )
ans += cur;
else
ans -= cur;
}
ans = ( ans % mod + mod ) % mod;
out.println( ans );
}
// void bf() {
// int[] ffff = new int[1<<cntBits];
// for (int ai : a) {
// for (int x = 0; x < ffff.length; x++) {
// if ((ai & x) == x) {
// ++ffff[x];
// }
// }
// }
// err.println(Arrays.toString(ffff));
//
// double ans = 0;
// for (int x = 0; x < ffff.length; x++) {
// ans += pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]);
// out.printf("%4s %d %3.0f\n",
// Integer.toBinaryString(x),
// ffff[x],
// pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]));
// }
// out.println(ans);
// }
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 7891c32362aeca0c875dfcc7271a177d | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import static java.lang.Math.pow;
import java.math.BigInteger.*;
import static java.math.BigInteger.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.fill;
//<editor-fold defaultstate="collapsed" desc="Imports">
//</editor-fold>
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
//<editor-fold defaultstate="collapsed" desc="Main">
public class Main {
private void run() {
Locale.setDefault(Locale.US);
boolean oj = true;
try {
oj = System.getProperty("MYLOCAL") == null;
} catch (Exception e) {
}
if (oj) {
sc = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
} else {
try {
sc = new FastScanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
MLE();
}
}
Solver s = new Solver();
s.sc = sc;
s.out = out;
s.solve();
err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
out.flush();
}
private void show(int[] arr) {
for (int v : arr) {
err.print(" " + v);
}
err.println();
}
public static void MLE() {
// int[][] arr = new int[1024 * 1024][];
// for (int i = 0; i < arr.length; i++) {
// arr[i] = new int[1024 * 1024];
// }
System.exit(0);
}
public static void main(String[] args) {
new Main().run();
}
long timeBegin = System.currentTimeMillis();
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader reader) {
br = new BufferedReader(reader);
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ex) {
Main.MLE();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
//</editor-fold>
class Solver {
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
final int cntBits = 20, mod = (int)1e9 + 7;
int n;
int[] a, ffff = new int[1<<cntBits];
int[][] f = new int[cntBits+1][1<<cntBits];
final long[] pow2 = new long[1<<cntBits];
{
pow2[0] = 1;
for (int i = 1; i < pow2.length; i++) {
pow2[i] = (pow2[i-1] * 2) % mod;
}
}
void solve(){
n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
++f[0][a[i]];
}
// bf();
for (int k = 1; k <= cntBits; k++) {
for (int msk = 0; msk < (1<<cntBits); msk++) {
if( (msk&(1<<(k-1))) == 0 )
f[k][msk] = (f[k-1][msk] + f[k-1][msk+(1<<(k-1))]) % mod;
else
f[k][msk] = f[k-1][msk];
}
}
// err.println(Arrays.toString(f[cntBits]));
long ans = 0;
for (int msk = 0; msk < (1<<cntBits); msk++) {
long cur = pow2[f[cntBits][msk]];
if( Integer.bitCount(msk)%2==0 )
ans += cur;
else
ans -= cur;
}
ans = ( ans % mod + mod ) % mod;
out.println( ans );
}
void bf() {
for (int ai : a) {
for (int x = 0; x < ffff.length; x++) {
if ((ai & x) == x) {
++ffff[x];
}
}
}
err.println(Arrays.toString(ffff));
double ans = 0;
for (int x = 0; x < ffff.length; x++) {
ans += pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]);
out.printf("%4s %d %3.0f\n",
Integer.toBinaryString(x),
ffff[x],
pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]));
}
out.println(ans);
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 4769f9b962919514e9bc9fa8a67d9718 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import static java.lang.Math.pow;
import java.math.BigInteger.*;
import static java.math.BigInteger.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.fill;
//<editor-fold defaultstate="collapsed" desc="Imports">
//</editor-fold>
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
//<editor-fold defaultstate="collapsed" desc="Main">
public class Main {
private void run() {
Locale.setDefault(Locale.US);
boolean oj = true;
try {
oj = System.getProperty("MYLOCAL") == null;
} catch (Exception e) {
}
if (oj) {
sc = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
} else {
try {
sc = new FastScanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
MLE();
}
}
Solver s = new Solver();
s.sc = sc;
s.out = out;
s.solve();
err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
out.flush();
}
private void show(int[] arr) {
for (int v : arr) {
err.print(" " + v);
}
err.println();
}
public static void MLE() {
// int[][] arr = new int[1024 * 1024][];
// for (int i = 0; i < arr.length; i++) {
// arr[i] = new int[1024 * 1024];
// }
System.exit(0);
}
public static void main(String[] args) {
new Main().run();
}
long timeBegin = System.currentTimeMillis();
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader reader) {
br = new BufferedReader(reader);
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ex) {
Main.MLE();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
//</editor-fold>
class Solver {
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
final int cntBits = 20, mod = (int)1e9 + 7;
int n;
int[] a;
int[] f = new int[1<<cntBits];
final long[] pow2 = new long[1<<cntBits];
{
pow2[0] = 1;
for (int i = 1; i < pow2.length; i++) {
pow2[i] = (pow2[i-1] * 2) % mod;
}
}
void solve(){
n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
++f[a[i]];
}
// bf();
for (int k = 1; k <= cntBits; k++) {
for (int msk = 0; msk < (1<<cntBits); msk++) {
if( (msk&(1<<(k-1))) == 0 )
f[msk] = (f[msk] + f[msk+(1<<(k-1))]) % mod;
}
}
// err.println(Arrays.toString(f[cntBits]));
long ans = 0;
for (int msk = 0; msk < (1<<cntBits); msk++) {
long cur = pow2[f[msk]];
if( Integer.bitCount(msk)%2==0 )
ans += cur;
else
ans -= cur;
}
ans = ( ans % mod + mod ) % mod;
out.println( ans );
}
// void bf() {
// int[] ffff = new int[1<<cntBits];
// for (int ai : a) {
// for (int x = 0; x < ffff.length; x++) {
// if ((ai & x) == x) {
// ++ffff[x];
// }
// }
// }
// err.println(Arrays.toString(ffff));
//
// double ans = 0;
// for (int x = 0; x < ffff.length; x++) {
// ans += pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]);
// out.printf("%4s %d %3.0f\n",
// Integer.toBinaryString(x),
// ffff[x],
// pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]));
// }
// out.println(ans);
// }
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | b2edb503943a0ef30e08752f5dc7b3f4 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.util.*;
import java.io.*;
public class a
{
public static void main(String[] arg) throws IOException
{
new a();
}
final long MOD = 1_000_000_007;
final int stop = 1_000_001;
long pow(long base, long exp)
{
if(exp == 0) return 1;
if((exp&1) != 0) return base*pow(base, exp-1)%MOD;
long ret = pow(base, exp/2);
return ret*ret%MOD;
}
public a() throws IOException
{
FastScanner in = new FastScanner(System.in);
int n = in.nextInt();
int[] dp = new int[stop];
for(int i = 0; i < n; i++) dp[in.nextInt()]++;
for(int i = 0; i < 20; i++)
{
for(int bm = 0; bm < stop; bm++)
{
if(((1<<i)&bm) != 0)
{
dp[bm^(1<<i)] += dp[bm];
}
}
}
long ans = 0;
long[] two = new long[stop];
two[0] = 1;
for(int i = 1; i < two.length; i++)
{
two[i] = two[i-1]*2%MOD;
}
for(int bm = 0; bm < stop; bm++)
{
if(Integer.bitCount(bm)%2 == 0)
{
ans += two[(int)dp[bm]]-1;
ans %= MOD;
}
else
{
ans -= two[(int)dp[bm]]-1;
ans += MOD;
ans %= MOD;
}
}
System.out.println(ans);
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException
{
while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
}
} | Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 44f756ece9c246669fee31486a8e33f1 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.util.*;
import java.io.*;
public class a
{
public static void main(String[] arg) throws IOException
{
new a();
}
final long MOD = 1_000_000_007;
final int stop = 1_000_001;
long pow(long base, long exp)
{
if(exp == 0) return 1;
if((exp&1) != 0) return base*pow(base, exp-1)%MOD;
long ret = pow(base, exp/2);
return ret*ret%MOD;
}
public a() throws IOException
{
FastScanner in = new FastScanner(System.in);
int n = in.nextInt();
int[] dp = new int[stop];
for(int i = 0; i < n; i++) dp[in.nextInt()]++;
for(int i = 0; i < 20; i++)
{
for(int bm = 0; bm < stop; bm++)
{
if(((1<<i)&bm) != 0)
{
dp[bm^(1<<i)] += dp[bm];
}
}
}
long ans = 0;
long[] two = new long[stop];
two[0] = 1;
for(int i = 1; i < two.length; i++)
{
two[i] = two[i-1]*2%MOD;
}
for(int bm = 0; bm < stop; bm++)
{
if(Integer.bitCount(bm)%2 == 0)
{
ans += two[(int)dp[bm]];
ans %= MOD;
}
else
{
ans -= two[(int)dp[bm]];
ans += MOD;
ans %= MOD;
}
}
ans++;
ans %= MOD;
System.out.println(ans);
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException
{
while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
}
} | Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | b32b3b85a189b881f0f1d5d17961367e | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Stack;
public class Main implements Runnable
{
static final int MAX = 1000000007;
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public boolean ready(){
try {
return br.ready();
} catch (IOException e) {
return false;
}
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<26).start();
}
int a;
int b;
final int bit = 20;
public void run()
{
InputReader sc= new InputReader(System.in);
PrintWriter w= new PrintWriter(System.out);
int n = sc.nextInt();
int[] arr= new int[(1<<(bit))];
int[] inp = new int[n];
for(int i = 0;i < n;i++){
inp[i] = sc.nextInt();
arr[inp[i]]++;
}
int[] ans = new int[(1<<bit)];
for(int i = 0;i < (1<<bit);i++){
ans[i] = arr[i];
}
for(int i = 0;i < bit;i++){
for(int j = 0;j < (1<<bit);j++){
if((j & (1<<i)) != 0){
ans[j^(1<<i)] += ans[j];
}
}
}
fun();
long an = 0;
for(int i = 0;i < (1<<bit);i++){
int nbits = Integer.bitCount(i);
long add = pow[ans[i]] + MAX - 1;
if(nbits % 2 == 0){
an = (an + add)%MAX;
}else{
an = (an + MAX - add)%MAX;
}
}
w.println(an);
w.close();
}
long pow[] = new long[1000005];
void fun(){
pow[0] = 1;
for(int i = 1;i < pow.length;i++){
pow[i] = (pow[i-1] * 2)%MAX;
}
}
long power(int n,int m){
long res = 1;
n = (n) % MAX;
while(m > 0){
if((m & 1) == 1){
res = (res * n) %MAX;
}
m = m >> 1;
n = (n * n) % MAX;
}
return res;
}
static class Pair implements Comparable<Pair>{
double a;
double b;
Pair(double a,double b){
this.a = a;
this.b = b;
}
public boolean equals(Object o)
{
Pair p = (Pair)o;
return (p.a==this.a && p.b== this.b);
}
public int compareTo(Pair p){
return Double.compare(this.a,p.a);
}
public int hashCode()
{
return new Double(a).hashCode()*31 + new Double(b).hashCode()*17;
}
}
} | Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | e417f5f415b98ad11375dc2c0d1faec7 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF449D extends PrintWriter {
CF449D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF449D o = new CF449D(); o.main(); o.flush();
}
static final int MD = 1000000007;
int count1(int a) {
return a == 0 ? 0 : count1(a & a - 1) + 1;
}
long power(int a, int k) {
if (k == 0)
return 1;
long p = power(a, k / 2);
p = p * p % MD;
if (k % 2 == 1)
p = p * a % MD;
return p;
}
void main() {
int n = sc.nextInt();
int[] dp = new int[1 << 20];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
dp[a]++;
}
for (int h = 0; h < 20; h++)
for (int a = 0; a < 1 << 20; a++)
if ((a & 1 << h) != 0)
dp[a ^ 1 << h] += dp[a];
int ans = 0;
for (int a = 0; a < 1 << 20; a++) {
int cnt = (int) power(2, dp[a]) - 1;
ans = (count1(a) % 2 == 0 ? ans + cnt : ans - cnt) % MD;
}
if (ans < 0)
ans += MD;
println(ans);
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | dca7452e5f7fdbb52b7b7c18ecbd0ffe | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class p0449D {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line;
line = br.readLine().split(" ");
int N = Integer.parseInt(line[0]);
line = br.readLine().split(" ");
int[][] fSub = new int[21][1<<20];
for(int n=0;n<N;n++){
fSub[0][Integer.parseInt(line[n])]++;
}
for(int k = 1; k <= 20; k++){
for(int x = 0; x < (1<<20); x++){
fSub[k][x] = fSub[k-1][x];
if(((x >> (k-1)) & 1) == 0){
fSub[k][x] += fSub[k-1][x+(1<<(k-1))];
}
}
}
int evenAns = 0;
int oddAns = 0;
for(int x = 0; x < (1<<20); x++){
if((Integer.bitCount(x) & 1) == 0){
evenAns = (evenAns + (int)pow(2, fSub[20][x])) % 1_000_000_007;
}
else{
oddAns = (oddAns + (int)pow(2, fSub[20][x])) % 1_000_000_007;
}
}
System.out.println((evenAns + 1_000_000_007 - oddAns) % 1_000_000_007);
}
static long pow(int base, int exp){
if(exp == 0){
return 1L;
}
long ret = pow(base, exp/2);
ret = ret * ret % 1_000_000_007;
if(((exp >> 1) << 1) != exp){
ret = ret * base % 1_000_000_007;
}
return ret;
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | eccec7db3ce73506c851f5cdf762b4ae | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes |
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
public class CF449D {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
Modular mod = new Modular(1000000007);
int[] pow2;
int limit = 1 << 20;
int[] cnts;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
public void solve() {
int n = io.readInt();
int[] A = new int[n];
for (int i = 0; i < n; i++) {
A[i] = io.readInt();
}
pow2 = new int[limit];
pow2[0] = 1;
for (int i = 1; i < limit; i++) {
pow2[i] = mod.mul(pow2[i - 1], 2);
}
cnts = new int[limit];
for (int i = 0; i < n; i++) {
cnts[A[i]]++;
}
FastWalshHadamardTransform.AndFWT(cnts, 0, limit - 1, mod);
int ans = inclusiveExclusive(20, 0, 0);
io.cache.append(ans);
}
public int inclusiveExclusive(int i, int or, int cnt) {
if (or >= limit) {
return 0;
}
if (i < 0) {
// if (cnts[or] > 0) {
// debug.debug("or", or);
// debug.debug("cnt", cnts[or]);
// }
if (cnt % 2 == 0) {
return mod.subtract(pow2[cnts[or]], 1);
} else {
return mod.valueOf(-mod.subtract(pow2[cnts[or]], 1));
}
}
int ans = mod.plus(inclusiveExclusive(i - 1, or, cnt), inclusiveExclusive(i - 1, or | (1 << i), cnt + 1));
return ans;
}
}
/**
* Mod operations
*/
public static class Modular {
int m;
public Modular(int m) {
this.m = m;
}
public int valueOf(int x) {
x %= m;
if (x < 0) {
x += m;
}
return x;
}
public int valueOf(long x) {
x %= m;
if (x < 0) {
x += m;
}
return (int) x;
}
public int mul(int x, int y) {
return valueOf((long) x * y);
}
public int mul(long x, long y) {
x = valueOf(x);
y = valueOf(y);
return valueOf(x * y);
}
public int plus(int x, int y) {
return valueOf(x + y);
}
public int plus(long x, long y) {
x = valueOf(x);
y = valueOf(y);
return valueOf(x + y);
}
public int subtract(int x, int y) {
return valueOf(x - y);
}
public int subtract(long x, long y) {
return valueOf(x - y);
}
@Override
public String toString() {
return "mod " + m;
}
}
public static class FastWalshHadamardTransform {
public static void OrFWT(int[] p, int l, int r) {
if (l == r) {
return;
}
int m = (l + r) >> 1;
OrFWT(p, l, m);
OrFWT(p, m + 1, r);
for (int i = 0, until = m - l; i <= until; i++) {
int a = p[l + i];
int b = p[m + 1 + i];
p[m + 1 + i] = a + b;
}
}
public static void OrIFWT(int[] p, int l, int r) {
if (l == r) {
return;
}
int m = (l + r) >> 1;
for (int i = 0, until = m - l; i <= until; i++) {
int a = p[l + i];
int b = p[m + 1 + i];
p[m + 1 + i] = b - a;
}
OrIFWT(p, l, m);
OrIFWT(p, m + 1, r);
}
public static void AndFWT(int[] p, int l, int r, Modular mod) {
if (l == r) {
return;
}
int m = (l + r) >> 1;
AndFWT(p, l, m, mod);
AndFWT(p, m + 1, r, mod);
for (int i = 0, until = m - l; i <= until; i++) {
int a = p[l + i];
int b = p[m + 1 + i];
p[l + i] = mod.plus(a, b);
}
}
public static void AndIFWT(int[] p, int l, int r) {
if (l == r) {
return;
}
int m = (l + r) >> 1;
for (int i = 0, until = m - l; i <= until; i++) {
int a = p[l + i];
int b = p[m + 1 + i];
p[l + i] = a - b;
}
AndIFWT(p, l, m);
AndIFWT(p, m + 1, r);
}
public static void XorFWT(int[] p, int l, int r) {
if (l == r) {
return;
}
int m = (l + r) >> 1;
XorFWT(p, l, m);
XorFWT(p, m + 1, r);
for (int i = 0, until = m - l; i <= until; i++) {
int a = p[l + i];
int b = p[m + 1 + i];
p[l + i] = a + b;
p[m + 1 + i] = a - b;
}
}
public static void XorIFWT(int[] p, int l, int r) {
if (l == r) {
return;
}
int m = (l + r) >> 1;
for (int i = 0, until = m - l; i <= until; i++) {
int a = p[l + i];
int b = p[m + 1 + i];
p[l + i] = (a + b) / 2;
p[m + 1 + i] = (a - b) / 2;
}
XorIFWT(p, l, m);
XorIFWT(p, m + 1, r);
}
public static void DotMul(int[] a, int[] b, int n) {
for (int i = 0; i < n; i++) {
a[i] = a[i] * b[i];
}
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder(1 << 13);
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() throws IOException {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
}
public boolean hasMore() {
skipBlank();
return next != -1;
}
}
public static class Debug {
private boolean allowDebug;
public Debug(boolean allowDebug) {
this.allowDebug = allowDebug;
}
public void assertTrue(boolean flag) {
if (!allowDebug) {
return;
}
if (!flag) {
fail();
}
}
public void fail() {
throw new RuntimeException();
}
public void assertFalse(boolean flag) {
if (!allowDebug) {
return;
}
if (flag) {
fail();
}
}
private void outputName(String name) {
System.out.print(name + " = ");
}
public void debug(String name, int x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, long x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, double x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, int[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, long[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, double[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, Object x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, Object... x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.deepToString(x));
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 09622305adf6ce19eb461e08789250d9 | train_003.jsonl | 1405774800 | Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*; import java.util.*;
public class CF0449D {
static int MXBIT=20;
static int MAXN=1<<20;
static int MOD=1000000007;
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());
}
}
public static void main(String[] args) {
int[] pow2=new int[MAXN+1];
pow2[0]=1;
for (int i = 1; i <=MAXN; i++) {
pow2[i]=(pow2[i-1]*2)%MOD;
}
FastReader br=new FastReader();
int N=br.nextInt();
int[] dp=new int[MAXN];
for (int i = 0; i < N; i++) {
dp[br.nextInt()]++;
//Evaluates f(mask,0)
}
for (int i = 0; i < MXBIT; i++) {
for (int mask = 0; mask < MAXN; mask++) {//Memory compressed:
//After processing i, everything is updated
if((mask&(1<<i))==0){
dp[mask]+=dp[mask|(1<<i)];
}
}
}
int ans=0;
for (int mask = 0; mask < MAXN; mask++) {
if(Integer.bitCount(mask)%2==1){
ans-=pow2[dp[mask]];
}else{
ans+=pow2[dp[mask]];
}
ans%=MOD;
}
if(ans<0){
ans+=MOD;
}
System.out.println(ans);
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). | standard output | |
PASSED | 8bbd2edeacc8ac35a180ca14f1bb8fe8 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mthai
*/
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);
CF_444A solver = new CF_444A();
solver.solve(1, in, out);
out.close();
}
static class CF_444A {
public void solve(int testNumber, Scanner input, PrintWriter out) {
ShortScanner in = new ShortScanner(input);
int n = in.i(), m = in.i();
int[] a = new int[n + 1];
for (int i = 1; i <= n; ++i) a[i] = in.i();
int[][] g = new int[n + 1][n + 1];
for (int i = 0; i < m; ++i) {
int x = in.i(), y = in.i(), c = in.i();
g[x][y] = g[y][x] = c;
}
double max = 0;
//for(int i = 1; i <= n; ++i) max = Math.max(a[i], max);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (g[i][j] == 0) continue;
max = Math.max(1.0 * (a[i] + a[j]) / g[i][j], max);
}
}
out.printf("%.15f\n", max);
}
class ShortScanner {
Scanner in;
ShortScanner(Scanner in) {
this.in = in;
}
int i() {
return in.nextInt();
}
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | a76d652100af7580d3520163ec2bec1c | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Alex
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out){
int nnodes = in.ri(), medges = in.ri();
int[] x = IOUtils.readIntArray(in, nnodes);
double ans = 0;
for(int i = 0; i < medges; i++) {
int a = in.ri()-1, b = in.ri()-1, c = in.ri();
ans = Math.max(ans, 1.0*(x[a]+x[b])/c);
}
out.printLine(ans);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ri(){
return readInt();
}
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);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 5cc0990ceda5379fdfcc04c3998f9a56 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt();
int[] v = new int[n];
for (int i = 0; i < n; i++)
v[i] = in.nextInt();
double res = 0;
for (int i = 0; i < m; i++) {
int x = in.nextInt() - 1, y = in.nextInt() - 1, e = in.nextInt();
res = Math.max(res, (v[x] + v[y]) / (double)e);
}
out.write(String.valueOf(res) + "\n");
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 69d9c33889a9eb1fd5f309cffbc57258 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
IIO io;
Main(IIO io){
this.io = io;
}
public static void main(String[] args) throws IOException {
Main m = new Main(new ConsoleIO());
m.solve();
// Tester test = new Tester();
// test.run();
}
public void solve() {
int[] a = io.readIntArray();
int[] nodes = io.readIntArray();
int num = 0;
int den = 1;
for (int i = 0; i < a[1]; i++) {
int[] edge = io.readIntArray();
int q = nodes[edge[0] - 1] + nodes[edge[1] - 1];
int w = edge[2];
if (q * den > w * num) {
num = q;
den = w;
}
}
io.writeLine(Double.toString((double) num / den));
}
}
class ConsoleIO extends BaseIO {
BufferedReader br;
public ConsoleIO(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public void writeLine(String s) {
System.out.println(s);
}
public String readLine() {
try {
return br.readLine();
}
catch (Exception ex){
return "";
}
}
}
abstract class BaseIO implements IIO {
@Override
public int readInt() {
return Integer.parseInt(this.readLine());
}
@Override
public int[] readIntArray() {
String line = this.readLine();
String[] nums = line.split(" ");
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
res[i] = Integer.parseInt(nums[i]);
}
return res;
}
}
interface IIO {
void writeLine(String s);
String readLine();
int readInt();
int[] readIntArray();
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | c487c6e2d21c9609aad52f5f66c1a16b | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.*;
import java.io.*;
public class DZYLovesPhysics {
public static InputReader in;
public static PrintWriter out;
public static final int myMotivation = 0;
public static final int MOD = (int) (1e9 + 7);
public static void main(String[] args) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt(), m = in.nextInt();
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
}
double ans = 0;
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1, c = in.nextInt();
ans = Math.max(ans, (x[a] + x[b])/(1.0*c));
}
out.println(ans);
out.close();
}
static class Node implements Comparable<Node> {
int next;
int dist;
public Node(int u, int v) {
this.next = u;
this.dist = v;
}
public void print() {
out.println(next + " " + dist + " ");
}
public int compareTo(Node that) {
return Integer.compare(this.next, that.next);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | fb7ac72f715a6a522119d353b88e7df3 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.StringTokenizer;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Solution {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out)) {
int n = nextInt(reader);
int m = nextInt(reader);
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt(reader);
}
double answer = 0;
for (int i = 0; i < m; i++) {
answer = Math.max(answer, (double)(a[nextInt(reader) - 1] + a[nextInt(reader) - 1]) / nextInt(reader));
}
writer.printf("%.10f\n", answer);
}
}
private static StringTokenizer stringTokenizer;
private static String next(BufferedReader reader) throws IOException {
if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
private static int nextInt(BufferedReader reader) throws IOException {
return Integer.parseInt(next(reader));
}
private static long nextLong(BufferedReader reader) throws IOException {
return Long.parseLong(next(reader));
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | b06e3e30b47001b1ccaaf9f7139d1178 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.TreeSet;
/**
* Created by hama_du on 15/08/03.
*/
public class A {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
int[] d = new int[n];
for (int i = 0; i < n ; i++) {
d[i] = in.nextInt();
}
double max = 0;
for (int i = 0; i < m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
int c = in.nextInt();
max = Math.max(max, 1.0d * (d[a] + d[b]) / c);
}
out.println(max);
out.flush();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int next() {
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 char nextChar() {
int c = next();
while (isSpaceChar(c))
c = next();
if ('a' <= c && c <= 'z') {
return (char) c;
}
if ('A' <= c && c <= 'Z') {
return (char) c;
}
throw new InputMismatchException();
}
public String nextToken() {
int c = next();
while (isSpaceChar(c))
c = next();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = next();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | dbc6272c14b9970e24e5e4240ecd17d8 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
}
double ans = 0;
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int c = in.nextInt();
ans = Math.max(ans, (double)(x[a] + x[b]) / c);
}
out.printf("%.15f\n", ans);
}
}
class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | ea71c46fd5a072dd2c5a055afa2dce4c | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int[] x = new int[n];
int sumV = 0;
for (int i = 0; i < n; i++) {
x[i] = nextInt();
sumV += x[i];
}
double ans = 0;
int sumE = 0;
for (int i = 0; i < m; i++) {
int v1 = nextInt() - 1;
int v2 = nextInt() - 1;
int xx = nextInt();
ans = Math.max(ans, 1.0 * (x[v1] + x[v2]) / xx);
}
out.println(ans);
}
A() 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 A();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 5db10f96908d5f811bbb057b7450dd55 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.PriorityQueue;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kanak893
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader fi, PrintWriter out) {
int n, m, i, j, a, b;
n = fi.nextInt();
m = fi.nextInt();
double nodeval[] = new double[n + 1];
for (i = 1; i <= n; i++) {
nodeval[i] = fi.nextInt();
}
PriorityQueue<Edge> pq = new PriorityQueue<>();
for (i = 0; i < m; i++) {
pq.add(new Edge(fi.nextInt(), fi.nextInt(), fi.nextInt()));
}
double ans = 0;
while (!pq.isEmpty()) {
Edge e = pq.poll();
a = e.a;
b = e.b;
double temp = (double) (nodeval[a] + nodeval[b]) / ((double) e.weight);
ans = Math.max(ans, temp);
}
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class Edge implements Comparable<Edge> {
int a;
int b;
int weight;
Edge(int a, int b, int weight) {
this.a = a;
this.b = b;
this.weight = weight;
}
public int compareTo(Edge x) {
return Integer.compare(this.weight, x.weight);
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 6288346ed7aed7d5e6e3e49c877185d3 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class C {
public static void main(String[] args) throws IOException {
int n = ConsoleIn.nextInt(), m = ConsoleIn.nextInt();
List<Integer> v = new ArrayList<>();
for (int i = 0; i < n; i++) {
int vv = ConsoleIn.nextInt();
v.add(vv);
}
int[][] a = new int[n][n];
double max = 0D;
for (int i = 0; i < m; i++) {
int f = ConsoleIn.nextInt() - 1, t = ConsoleIn.nextInt() - 1, val = ConsoleIn.nextInt();
a[f][t] = val;
a[t][f] = val;
double d = (v.get(f) + v.get(t) + 0.0) / (1.0 * val);
if (max < d) max = d;
}
System.out.printf("%.9f\n", max);
}
static class ConsoleIn {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
public static String nextString() throws IOException {
if (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public static float nextFloat() throws IOException {
return Float.parseFloat(nextString());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
public static int[] nextIntArray() throws IOException {
String[] ss = reader.readLine().split(" ");
int[] a = new int[ss.length];
for (int i = 0; i < ss.length; i++) a[i] = Integer.parseInt(ss[i]);
return a;
}
public static long[] nextLongArray() throws IOException {
String[] ss = reader.readLine().split(" ");
long[] a = new long[ss.length];
for (int i = 0; i < ss.length; i++) a[i] = Long.parseLong(ss[i]);
return a;
}
public static double[] nextDoubleArray() throws IOException {
String[] ss = reader.readLine().split(" ");
double[] a = new double[ss.length];
for (int i = 0; i < ss.length; i++) a[i] = Double.parseDouble(ss[i]);
return a;
}
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 77b471cb21e7b674d1b6ac31f3e19073 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
int[] dx = {0, -1, 0, 1};
int[] dy = {1, 0, -1, 0};
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int[] arr = nextIntArr(n);
double res = 0;
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
int c = nextInt();
res = Math.max(res, 1.0 * (arr[u] + arr[v]) / c);
}
// out(String.format("%.10f", res));
out(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;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 9e6507446b9e17209b381e9faaf895f2 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
import static java.lang.Math.*;
public class CodeforcesA implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = readInt();
return array;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void main(String[] args) {
new Thread(null, new CodeforcesA(), "", 128 * (1L << 20)).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
+ " KB");
}
void debug(Object... objects) {
if (DEBUG) {
for (Object o : objects) {
System.err.println(o.toString());
}
}
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
time();
memory();
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
class Edge implements Comparable<Edge> {
int a, b, w;
public Edge(int a, int b, int w) {
super();
this.a = a;
this.b = b;
this.w = w;
}
@Override
public int compareTo(Edge o) {
return w - o.w;
}
}
boolean DEBUG = false;
void solve() throws IOException {
int n = readInt();
int m = readInt();
int[] x = readIntArray(n);
int[][] d = new int[n][n];
for (int i=0; i<m; i++) {
int a = readInt()-1;
int b = readInt()-1;
int weight =readInt();
d[a][b] = weight;
d[b][a] = weight;
}
int ansV = 0;
int ansE = 1;
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++)
if (d[i][j]>0) {
if (1l*(x[i] + x[j]) * ansE > 1l*d[i][j]*ansV) {
ansE = d[i][j];
ansV = x[i] + x[j];
}
}
out.println(1d*ansV / ansE);
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 656348b138e218f7ac7220aa745826e9 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author shu_mj @ http://shu-mj.com
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
Scanner in;
PrintWriter out;
public void solve(int testNumber, Scanner in, PrintWriter out) {
this.in = in;
this.out = out;
run();
}
void run() {
int n = in.nextInt();
int m = in.nextInt();
int[] vv = in.nextIntArray(n);
E[] es = new E[m];
for (int i = 0; i < m; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
int c = in.nextInt();
es[i] = new E(u, v, c, vv[u] + vv[v]);
}
if (m == 0) {
out.printf("%.15f%n", 0.0);
return ;
}
Arrays.sort(es, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return o1.vCost * o2.cost - o2.vCost * o1.cost;
}
});
out.printf("%.15f%n", es[m - 1].vCost * 1.0 / es[m - 1].cost);
}
class E {
int u;
int v;
int cost;
int vCost;
E(int u, int v, int cost, int vCost) {
this.u = u;
this.v = v;
this.cost = cost;
this.vCost = vCost;
}
}
}
class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
eat("");
}
private void eat(String s) {
st = new StringTokenizer(s);
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
public boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
public String next() {
hasNext();
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] is = new int[n];
for (int i = 0; i < n; i++) {
is[i] = nextInt();
}
return is;
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 8767decb099a5d27e030448044293624 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | //package net.dimatomp.cdf.upsolve.round444;
import java.io.*;
import java.util.*;
public class ProblemA {
FastScanner in;
PrintWriter out;
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
Locale.setDefault(Locale.US);
int n = in.nextInt(), m = in.nextInt();
int x[] = new int[n];
for (int i = 0; i < n; i++)
x[i] = in.nextInt();
double ans = 0;
for (int i = 0; i < m; i++)
ans = Double.max(ans, (x[in.nextInt() - 1] + x[in.nextInt() - 1]) / in.nextDouble());
out.printf("%.10f\n", ans);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ProblemA().run();
}
class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
FastScanner(String filename) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(filename));
}
String nextToken() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | c4eb54e07e4e0077ce48232fba52675d | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static void solve() throws Exception {
int n = nextInt();
int m = nextInt();
int[] x = new int[n+1];
for (int i = 1; i <= n; ++i) {
x[i] = nextInt();
}
int v = 0;
int e = 1;
for (int i = 1; i <= m; ++i) {
int a = nextInt();
int b = nextInt();
int c = nextInt();
if ((x[a] + x[b]) * e > v * c) {
v = x[a] + x[b];
e = c;
}
}
out.println(v /(double) e);
}
static int sqr(int x) {
return x*x;
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
static String next() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static String nextLine() throws IOException {
tok = new StringTokenizer("");
return in.readLine();
}
static boolean hasNext() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return false;
}
tok = new StringTokenizer(s);
}
return true;
}
public static void main(String args[]) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
//in = new BufferedReader(new FileReader("input.in"));
//out = new PrintWriter(new FileWriter("output.out"));
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
java.lang.System.exit(1);
}
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 112a963f246227d500c58ccc6ccf0733 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.Scanner;
public class DZYLovesPhysics {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int nums[] = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
double max = 0;
int a, b;
double c;
for (int i = 0; i < m; i++) {
a = sc.nextInt() - 1;
b = sc.nextInt() - 1;
c = sc.nextDouble();
max = Math.max(max, ((double) (nums[a] + nums[b])) / c);
}
System.out.println(max);
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | ee0f9de6f55298a6038c51ccce140ed3 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int m = readInt();
int[] list = new int[n];
for(int i = 0; i < n; i++) {
list[i] = readInt();
}
double ret = 0;
while(m-- > 0) {
int a = readInt()-1;
int b = readInt()-1;
int c = readInt();
ret = Math.max(ret, (list[a] + list[b]) / 1.0 / c);
}
pw.println(ret);
}
exitImmediately();
}
public static int need(int h, int a) {
return (h+a-1)/a;
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
if(!br.ready()) {
exitImmediately();
}
st = null;
return br.readLine();
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 6 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | f9f35d4b58b563ee302e198bc1296561 | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.*;
public class maximus {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int m=in.nextInt();
int array[]=new int[n+1];
for(int i=1;i<=n;i++)array[i]=in.nextInt();
double cnt=0;
for(int i=0;i<m;i++){
int a=in.nextInt();
int b=in.nextInt();
int c=in.nextInt();
cnt=Math.max(cnt,(double)(array[a] + array[b])/c);
}
System.out.print(cnt);
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 6 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | fc112e5baf220d2c34275cf8052448eb | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt(), m = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++) data[i] = input.nextInt();
ArrayList<Edge>[] g = new ArrayList[n];
for(int i = 0; i<n; i++) g[i] = new ArrayList<Edge>();
for(int i = 0; i<m; i++)
{
int a = input.nextInt()-1 ,b = input.nextInt()-1, c = input.nextInt();
g[a].add(new Edge(b, c));
g[b].add(new Edge(a, c));
}
double res = 0;
for(int i = 0; i<n; i++)
{
boolean[] set = new boolean[n];
int[] costs = new int[n];
Arrays.fill(costs, 987654321);
for(Edge e: g[i]) costs[e.to] = e.cost;
int num = data[i];
set[i] = true;
int denom = 0;
for(int iter = 1; iter < n; iter++)
{
int mindex = -1;
double max = denom == 0 ? 0 : 1.*num/denom;
for(int j = 0; j<n; j++)
{
if(set[j] || costs[j] == 987654321) continue;
if(1. * (num+data[j]) / (denom+costs[j]) > max)
{
max = 1. * (num+data[j]) / (denom+costs[j]);
mindex = j;
}
}
if(mindex == -1) break;
//out.println(i+" "+mindex);
set[mindex] = true;
denom += costs[mindex];
num+= data[mindex];
for(Edge e: g[mindex]) costs[e.to] += e.cost;
res = Math.max(res, 1.*num/denom);
}
}
out.println(res);
out.close();
}
static class Edge
{
int to, cost;
public Edge(int tt, int cc)
{
to = tt; cost = cc;
}
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 6 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 0e7ce0ce86f93e6e614bf2985793923e | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.Scanner;
public class A {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
int m =sc.nextInt();
int[] node = new int[n+1];
int[][] g = new int[n+1][n+1];
for(int i=0;i<n;i++){
node[i+1]=sc.nextInt();
}
for(int i=0;i<m;i++){
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
g[a][b]=g[b][a]=c;
}
double ans = 0;
for(int i=1;i<g.length;i++){
for(int j=1;j<g.length;j++){
if(g[i][j]==0.0)continue;
ans = Math.max(ans, (double)(node[i]+node[j])/(g[i][j]));
}
}
System.out.println(ans);
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 6 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 15a93394460a4f6d0d643b18c1fcd03a | train_003.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
InputStream inputStream = onlineJudge ? System.in : new FileInputStream("input.txt");
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(in, out);
out.close();
}
}
class Solver {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[] v = new int[n];
for (int i = 0; i < n; i++) {
v[i] = in.nextInt();
}
double ans = 0;
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int e = in.nextInt();
double cur = (v[a] + v[b]) / (double) e;
ans = Math.max(ans, cur);
}
out.printf("%.10f\n", ans);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 6 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. | standard output | |
PASSED | 2cd887e08dede93801c09fa356d8aab5 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.Scanner;
public class IgorToWork {
static char [][] grid;
static int endRow;
static int endCol;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
grid = new char[n][m];
int startRow = -1;
int startCol = -1;
for (int i = 0; i < n; i++) {
String line = scan.next();
for (int j = 0; j < m; j++) {
Character cell = line.charAt(j);
grid[i][j] = cell;
if (cell == 'S') {
startRow = i;
startCol = j;
}
else if (cell == 'T') {
endRow = i;
endCol = j;
}
}
}
dfs(startRow, startCol - 1, 0, 'L');
dfs(startRow, startCol + 1, 0, 'R');
dfs(startRow - 1, startCol, 0, 'U');
dfs(startRow + 1, startCol, 0, 'D');
System.out.println("NO");
}
static void dfs(int row, int col, int numTurns, char dir) {
// Outside grid
if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length) {
return;
}
// Too many turns
if (numTurns >= 3) {
return;
}
// Don't check if you can only go left/right and the answer is
// in a different row
if (numTurns == 2 && (dir == 'L' || dir == 'R') && row != endRow) {
return;
}
// Don't check if you can only go up/down and the answer is
// in a different column
if (numTurns == 2 && (dir == 'U' || dir == 'D') && col != endCol) {
return;
}
// Blocked
if (grid[row][col] == '*') {
return;
}
// Found a path
if (grid[row][col] == 'T') {
System.out.println("YES");
System.exit(0);
}
// left
if (dir == 'L') { // Don't turn right
dfs(row, col - 1, numTurns, 'L');
dfs(row - 1, col, numTurns + 1, 'U');
dfs(row + 1, col, numTurns + 1, 'D');
}
// right
if (dir == 'R') { // Don't turn left
dfs(row, col + 1, numTurns, 'R');
dfs(row - 1, col, numTurns + 1, 'U');
dfs(row + 1, col, numTurns + 1, 'D');
}
// up
if (dir == 'U') { // Don't go down
dfs(row - 1, col, numTurns, 'U');
dfs(row, col - 1, numTurns + 1, 'L');
dfs(row, col + 1, numTurns + 1, 'R');
}
// down
if (dir == 'D') { // Don't go up
dfs(row + 1, col, numTurns, 'D');
dfs(row, col - 1, numTurns + 1, 'L');
dfs(row, col + 1, numTurns + 1, 'R');
}
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | b62d3a7b49384c7903714d3747d2913f | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.*;
import java.io.*;
public class KTurnToOffice {
public static int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public static boolean dfs(char[][] matrix, int cur, int end, int d, int count, boolean[][][] visited) {
if (count > 2) return false;
if (cur == end) return true;
visited[cur][d][count] = true;
int m = matrix.length;
int n = matrix[0].length;
int x = cur / n;
int y = cur % n;
for (int k = 0; k < dir.length; k++) {
int X = x + dir[k][0];
int Y = y + dir[k][1];
int id = X * n + Y;
if (k == d) {
if (X < 0 || X >= m || Y < 0 || Y >= n || matrix[X][Y] == '*' || visited[id][k][count]) continue;
if (dfs(matrix, id, end, k, count, visited)) return true;
} else {
if (X < 0 || X >= m || Y < 0 || Y >= n || matrix[X][Y] == '*' || count == 2 || visited[id][k][count + 1]) continue;
if (dfs(matrix, id, end, k, count + 1, visited)) return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
char[][] matrix = new char[m][n];
int start = -1;
int terminal = -1;
for (int i = 0; i < m; i++) {
String line = sc.next();
for (int j = 0; j < n; j++) {
matrix[i][j] = line.charAt(j);
if (matrix[i][j] == 'S') start = i * n + j;
if (matrix[i][j] == 'T') terminal = i * n + j;
}
}
boolean flag = dfs(matrix, start, terminal, 0, 0, new boolean[m * n][4][3])
|| dfs(matrix, start, terminal, 1, 0, new boolean[m * n][4][3])
|| dfs(matrix, start, terminal, 2, 0, new boolean[m * n][4][3])
|| dfs(matrix, start, terminal, 3, 0, new boolean[m * n][4][3]);
if (flag) System.out.println("YES");
else System.out.println("NO");
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 01ee7df0d24557eded66444e1f77f564 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class F {
//Solution by Sathvik Kuthuru
public static void main(String[] args) {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
int t = 1;
for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out);
out.close();
}
static class Task {
int n, m;
char[][] s;
int sy, sx, ey, ex;
int[] dy = {-1, 0, 1, 0}, dx = {0, 1, 0, -1};
public void solve(int testNumber, FastReader scan, PrintWriter out) {
n = scan.nextInt();
m = scan.nextInt();
s = new char[n][m];
int[][][] dist = new int[n][m][4];
for(int i = 0; i < n; i++) {
s[i] = scan.next().toCharArray();
for(int j = 0; j < m; j++) {
Arrays.fill(dist[i][j], 100);
if(s[i][j] == 'S') {
sy = i;
sx = j;
}
else if(s[i][j] == 'T') {
ey = i;
ex = j;
}
}
}
boolean[][][] visited = new boolean[n][m][4];
PriorityQueue<Edge> queue = new PriorityQueue<>();
for(int i = 0; i < 4; i++) {
dist[sy][sx][i] = 0;
queue.add(new Edge(sy, sx, i, 0));
}
while(!queue.isEmpty()) {
Edge curr = queue.poll();
if(visited[curr.y][curr.x][curr.dir]) continue;
visited[curr.y][curr.x][curr.dir] = true;
//out.println(curr.y + " " + curr.x + " " + " " + curr.dir + " " + curr.weight);
for(int i = 0; i < 2; i++) {
int nextDir = (curr.dir + i) % 4;
if(curr.weight + 1 < dist[curr.y][curr.x][nextDir]) {
dist[curr.y][curr.x][nextDir] = curr.weight + 1;
queue.add(new Edge(curr.y, curr.x, nextDir, curr.weight + 1));
}
}
for(int i = 0; i < 2; i++) {
int nextDir = (curr.dir - i + 4) % 4;
if(curr.weight + 1 < dist[curr.y][curr.x][nextDir]) {
dist[curr.y][curr.x][nextDir] = curr.weight + 1;
queue.add(new Edge(curr.y, curr.x, nextDir, curr.weight + 1));
}
}
int nextY = curr.y + dy[curr.dir], nextX = curr.x + dx[curr.dir];
if(nextX >= 0 && nextY >= 0 && nextY < n && nextX < m && s[nextY][nextX] != '*') {
if(curr.weight < dist[nextY][nextX][curr.dir]) {
dist[nextY][nextX][curr.dir] = curr.weight;
queue.add(new Edge(nextY, nextX, curr.dir, curr.weight));
}
}
}
int res = Integer.MAX_VALUE;
for(int i = 0; i < 4; i++) res = Math.min(res, dist[ey][ex][i]);
if(res <= 2) out.println("YES");
else out.println("NO");
//out.println(res);
}
static class Edge implements Comparable<Edge> {
int y, x, dir, weight;
public Edge(int a, int b, int c, int d) {
y = a;
x = b;
dir = c;
weight = d;
}
@Override
public int compareTo(Edge edge) {
return Integer.compare(weight, edge.weight);
}
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | c3c729bd3841f82ec52f1193831e7049 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class IgorAndHisWayToWork {
private static int N;
private static int M;
private static final int MAX_TURNS = 2;
private static final int L = 2;
private static final int R = 3;
private static final int U = 4;
private static final int D = 5;
private static char[][] labyrinth;
private static int[][] flags;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] dimensions = br.readLine().split(" ");
N = Integer.parseInt(dimensions[0]);
M = Integer.parseInt(dimensions[1]);
labyrinth = new char[N][M];
flags = new int[N][M];
for (int i = 0; i < N; i++) {
labyrinth[i] = br.readLine().trim().toCharArray();
}
int[] home = getPositionLetter('S');
boolean res = itsPossible(home[0], home[1]);
System.out.println(res ? "YES" : "NO");
}
private static boolean itsPossible(int i, int j) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{i, j, 0});
try {
while (!queue.isEmpty()) {
int[] actualPoint = queue.poll();
int row = actualPoint[0];
int col = actualPoint[1];
int depth = actualPoint[2];
if (depth >= 3) break;
// if (flags[row][col] == 1) continue;
flags[row][col] = 1;
checkUp(row, col, depth, queue);
checkDown(row, col, depth, queue);
checkLeft(row, col, depth, queue);
checkRight(row, col, depth, queue);
}
} catch (Exception e) {
return true;
}
return false;
}
private static void checkRight(int row, int col, int depth, Queue<int[]> queue) throws Exception {
for (int i = col + 1; i < M; i++) {
if (flags[row][i] == R) break;
if (labyrinth[row][i] == '.') {
if (flags[row][i] == 0) {
if (row - 1 >= 0 && labyrinth[row - 1][i] != '*') {
queue.add(new int[]{row, i, depth + 1});
flags[row][i] = R;
}
else if (row + 1 < N && labyrinth[row + 1][i] != '*') {
queue.add(new int[]{row, i, depth + 1});
flags[row][i] = R;
}
}
} else if (labyrinth[row][i] == 'T') throw new Exception("c:");
else break;
flags[row][i] = R;
}
}
private static void checkLeft(int row, int col, int depth, Queue<int[]> queue) throws Exception {
for (int i = col - 1; i >= 0; i--) {
if (flags[row][i] == L) break;
if (labyrinth[row][i] == '.') {
if (flags[row][i] == 0) {
if (row - 1 >= 0 && labyrinth[row - 1][i] != '*') {
queue.add(new int[]{row, i, depth + 1});
flags[row][i] = L;
}
else if (row + 1 < N && labyrinth[row + 1][i] != '*') {
queue.add(new int[]{row, i, depth + 1});
flags[row][i] = L;
}
}
} else if (labyrinth[row][i] == 'T') throw new Exception("c:");
else break;
flags[row][i] = L;
}
}
private static void checkDown(int row, int col, int depth, Queue<int[]> queue) throws Exception {
for (int i = row + 1; i < N; i++) {
if (flags[i][col] == D) break;
if (labyrinth[i][col] == '.') {
if (flags[i][col] == 0) {
if (col - 1 >= 0 && labyrinth[i][col - 1] != '*') {
queue.add(new int[]{i, col, depth + 1});
flags[i][col] = D;
}
else if (col + 1 < M && labyrinth[i][col + 1] != '*') {
queue.add(new int[]{i, col, depth + 1});
flags[i][col] = D;
}
}
} else if (labyrinth[i][col] == 'T') throw new Exception("c:");
else break;
flags[i][col] = D;
}
}
private static void checkUp(int row, int col, int depth, Queue<int[]> queue) throws Exception {
for (int i = row - 1; i >= 0; i--) {
if (flags[i][col] == U) break;
if (labyrinth[i][col] == '.') {
if (flags[i][col] == 0) {
if (col - 1 >= 0 && labyrinth[i][col - 1] != '*') {
queue.add(new int[]{i, col, depth + 1});
flags[i][col] = U;
}
else if (col + 1 < M && labyrinth[i][col + 1] != '*') {
queue.add(new int[]{i, col, depth + 1});
flags[i][col] = U;
}
}
} else if (labyrinth[i][col] == 'T') throw new Exception("c:");
else break;
flags[i][col] = U;
}
}
private static int[] getPositionLetter(char s) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (labyrinth[i][j] == s) {
return new int[]{i, j};
}
}
}
return new int[]{-1, -1};
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 8debb84420b9a99fd0bf0a2654cc035a | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
*/
/**
* @author mohanad
*
WA expected YES found NO
3 3
...
.*.
T*S
*
*/
public class B {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String nm[]=bf.readLine().split(" ");
n=Integer.parseInt(nm[0]);
m=Integer.parseInt(nm[1]);
StringBuilder out=new StringBuilder();
int min=-1;
arr=new char[n][m];
for (int i = 0;i<n ; ++i){
String a=bf.readLine();
for (int j = 0 ;j<m ; ++j){
arr[i][j]=a.charAt(j);
if (arr[i][j]=='S'){
si=i;
sj=j;
}
}
}
visited=new boolean [1005][1005][6][4];
System.out.println(found((byte)-1, si, sj, (byte)-1)>0?"YES":"NO");
}
static char arr[][];
static int n ,m,si,sj , don=0 ;
static boolean visited[][][][];
static int found (byte last , int r , int c , byte count){
if (don==1 ||!isvalid(r, c) || arr[r][c]=='*' || count>2){
return 0;
}
if (arr[r][c]=='T'){
don=1;
return 1;
}
if (count!=-1 &&visited[r][c][last][count])
return 0;
if (count!=-1)
visited[r][c][last][count]=true;
int U=found((byte)3, r-1, c, (byte)((last==3)?count:count+1));
int R=found((byte)0, r, c+1, (byte)((last==0)?count:count+1));
int L=found((byte)1, r, c-1, (byte)((last==1)?count:count+1));
int D=found((byte)2, r+1, c, (byte)((last==2)?count:count+1));
return R+L+D+U;
}
static boolean isvalid (int r , int c){
if (r<0 || r>=n || c<0 || c>=m)
return false;
return true;
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | d69553c7dc9736564b12c82fecf71732 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
static ArrayList<Integer>adj[];
static PrintWriter out=new PrintWriter(System.out);
public static int mod = 1000000007;
static char s[];
static char u[];
static int notmemo[][][];
static ArrayList<Edge> drivers[];
public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
grid=new char[n][m];
pq=new PriorityQueue<Quad>();
for(int i=0 ; i<n ; i++) {
char c[]=sc.nextLine().toCharArray();
for (int j = 0; j < c.length; j++) {
grid[i][j]=c[j];
if(grid[i][j]=='S') {
pq.add(new Quad(i,j,'o',0));
}
}
}
floodfillbfs();
}
static int dx[]= {0,0,1,-1};
static int dy[]= {1,-1,0,0};
static char grid[][];
static PriorityQueue<Quad> pq;
static int m;
static void floodfillbfs() {
boolean vis[][][]=new boolean[n][m][3];
while(!pq.isEmpty()) {
Quad q=pq.poll();
if(q.turns>2) {
continue;
}
else if(grid[q.u][q.v]=='T') {
System.out.println("YES");
return;
}
int curx=q.u;
int cury=q.v;
vis[curx][cury][q.turns]=true;
for (int i = 0; i <4; i++) {
int x=curx+dx[i];
int y=cury+dy[i];
if(x>=0&&y>=0 &&x<n&&y<m&&!vis[x][y][q.turns]&&grid[x][y]!='*') {
if(x!=curx&&(q.state=='o'||q.state=='l')) {
pq.add(new Quad(x,y,'l', q.turns)) ;
}
else if(y!=cury&&(q.state=='o'||q.state=='u')) {
pq.add(new Quad(x,y,'u', q.turns)) ;
}
else if(y!=cury&&q.state=='l') {
pq.add(new Quad(x,y,'u', q.turns+1)) ;
}
else if(x!=curx&&q.state=='u') {
pq.add(new Quad(x,y,'l', q.turns+1)) ;
}
}
}
}
System.out.println("NO");
return;
}
static class Quad implements Comparable<Quad>{
int u;
int v;
char state;
int turns;
public Quad(int i, int j, char c, int k) {
u=i;
v=j;
state=c;
turns=k;
}
public int compareTo(Quad e){ return (int) (turns - e.turns); }
}
static long dirg[][];
static Edge[] driver;
static int n;
static class Edge implements Comparable<Edge>
{
int node; long cost;
Edge(int a, long dirg) { node = a; cost = dirg; }
public int compareTo(Edge e){ return (int) (cost - e.cost); }
}
public static int dp(int i, int j,int found) {
if(i==s.length||j==u.length) {
return 0;
}
int max=0;
if(notmemo[i][j][found]!=-1) {
return notmemo[i][j][found];
}
if(s[i]==u[j]&&found==1) {
max=Math.max(dp(i+1,j+1,1)+1,max);
}
else if(found==1) {
max=Math.max(dp(i+1,j+1,1),max);
}
else if(s[i]==u[j]&&found==0)
max=Math.max(dp(i+1,j+1,1)+1,max);
if(found==0) {
max=Math.max(dp(i,j+1,0),max);
max=Math.max(dp(i+1,j,0),max);
}
return notmemo[i][j][found]=max;
}
static long manhatandistance(long x,long x2,long y,long y2) {
return Math.abs(x-x2)+Math.abs(y-y2);
}
static long fib[];
static long fib(int n) {
if(n==1||n==0) {
return 1;
}
if(fib[n]!=-1) {
return fib[n];
}
else
return fib[n]= ((fib(n-2)%mod+fib(n-1)%mod)%mod);
}
static class Pair implements Comparable<Pair>{
int skill;
int idx;
Pair(int a, int b){
skill=a;
idx=b;
}
public int compareTo(Pair p) {
return p.skill-this.skill;
}
}
static long[][] comb;
static long nCr1(int n , int k)
{
if(n < k)
return 0;
if(k == 0 || k == n)
return 1;
if(comb[n][k] != -1)
return comb[n][k];
if(n - k < k)
return comb[n][k] = nCr1(n, n - k);
return comb[n][k] = (nCr1(n - 1, k - 1) + nCr1(n - 1, k))%mod;
}
static class Triple implements Comparable<Triple>{
int u;
int v;
long totalcost;
public Triple(int a,int b,long l) {
u=a;
v=b;
totalcost=l;
}
@Override
public int compareTo(Triple o) {
return Long.compare( totalcost,o.totalcost);
}
}
static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N))
{
TreeSet<Long> factors = new TreeSet<Long>(); //take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while(p * p <= N)
{
while(N % p == 0) { factors.add((long) p); N /= p; }
if(primes.size()>idx+1)
p = primes.get(++idx);
else
break;
}
if(N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static boolean visited[];
/**static int bfs(int s)
{
Queue<Integer> q = new LinkedList<Integer>();
q.add(s);
int count=0;
int maxcost=0;
int dist[]=new int[n];
dist[s]=0;
while(!q.isEmpty())
{
int u = q.remove();
if(dist[u]==k) {
break;
}
for(Pair v: adj[u])
{
maxcost=Math.max(maxcost, v.cost);
if(!visited[v.v]) {
visited[v.v]=true;
q.add(v.v);
dist[v.v]=dist[u]+1;
maxcost=Math.max(maxcost, v.cost);
}
}
}
return maxcost;
}**/
public static boolean FindAllElements(int n, int k) {
int sum = k;
int[] A = new int[k];
Arrays.fill(A, 0, k, 1);
for (int i = k - 1; i >= 0; --i) {
while (sum + A[i] <= n) {
sum += A[i];
A[i] *= 2;
}
}
if(sum==n) {
return true;
}
else
return false;
}
static long[][] memo;
static boolean vis2[][];
static class SegmentTree { // 1-based DS, OOP
int N; //the number of elements in the array as a power of 2 (i.e. after padding)
int[] array, sTree, lazy;
SegmentTree(int[] in)
{
array = in; N = in.length - 1;
sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new int[N<<1];
build(1,1,N);
}
void build(int node, int b, int e) // O(n)
{
if(b == e)
sTree[node] = array[b];
else
{
int mid = b + e >> 1;
build(node<<1,b,mid);
build(node<<1|1,mid+1,e);
sTree[node] = sTree[node<<1]+sTree[node<<1|1];
}
}
void update_point(int index, int val) // O(log n)
{
index += N - 1;
sTree[index] += val;
while(index>1)
{
index >>= 1;
sTree[index] = sTree[index<<1] + sTree[index<<1|1];
}
}
void update_range(int i, int j, int val) // O(log n)
{
update_range(1,1,N,i,j,val);
}
void update_range(int node, int b, int e, int i, int j, int val)
{
if(i > e || j < b)
return;
if(b >= i && e <= j)
{
sTree[node] += (e-b+1)*val;
lazy[node] += val;
}
else
{
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node<<1,b,mid,i,j,val);
update_range(node<<1|1,mid+1,e,i,j,val);
sTree[node] = sTree[node<<1] + sTree[node<<1|1];
}
}
void propagate(int node, int b, int mid, int e)
{
lazy[node<<1] += lazy[node];
lazy[node<<1|1] += lazy[node];
sTree[node<<1] += (mid-b+1)*lazy[node];
sTree[node<<1|1] += (e-mid)*lazy[node];
lazy[node] = 0;
}
int query(int i, int j)
{
return query(1,1,N,i,j);
}
int query(int node, int b, int e, int i, int j) // O(log n)
{
if(i>e || j <b)
return 0;
if(b>= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
propagate(node, b, mid, e);
int q1 = query(node<<1,b,mid,i,j);
int q2 = query(node<<1|1,mid+1,e,i,j);
return q1 + q2;
}
}
static boolean f2=false;
static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) //C(p x r) = A(p x q) x (q x r) -- O(p x q x r)
{
long[][] C = new long[p][r];
for(int i = 0; i < p; ++i) {
for(int j = 0; j < r; ++j) {
for(int k = 0; k < q; ++k) {
C[i][j] = (C[i][j]+(a2[i][k]%mod * b[k][j]%mod))%mod;
C[i][j]%=mod;
}
}
}
return C;
}
static ArrayList<Pair> a1[];
static int memo1[];
static boolean vis[];
static TreeSet<Integer> set=new TreeSet<Integer>();
static long modPow(long ways, long count, long mod) // O(log e)
{
ways %= mod;
long res = 1;
while(count > 0)
{
if((count & 1) == 1)
res = (res * ways) % mod;
ways = (ways * ways) % mod;
count >>= 1;
}
return res%mod;
}
static long gcd(long ans,long b) {
if(b==0) {
return ans;
}
return gcd(b,ans%b);
}
static int[] isComposite;
static int[] valid;
static ArrayList<Integer> primes;
static ArrayList<Integer> l;
static void sieve(int N) // O(N log log N)
{
isComposite = new int[N+1];
isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number
primes = new ArrayList<Integer>();
l=new ArrayList<>();
valid=new int[N+1];
for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N))
if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance
{
primes.add(i);
l.add(i);
valid[i]=1;
for (int j = i*2; j <=N; j +=i) { // j = i * 2 will not affect performance too much, may alter in modified sieve
isComposite[j] = 1;
}
}
for(int i=0 ; i<primes.size() ; i++) {
for(int j:primes) {
if(primes.get(i)*j>N) {
break;
}
valid[primes.get(i)*j]=1;
}
}
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
public UnionFind(int N)
{
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; }
}
public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }
public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public boolean unionSet(int i, int j)
{
if (isSameSet(i, j))
return false;;
numSets--;
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
else
{ p[x] = y; setSize[y] += setSize[x];
if(rank[x] == rank[y]) rank[y]++;
}
return true;
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
public static int[] schuffle(int[] a2) {
for (int i = 0; i < a2.length; i++) {
int x=(int)(Math.random()*a2.length);
int temp=a2[x];
a2[x]=a2[i];
a2[i]=temp;
}
return a2;
}
static int V;
static long INF=(long) 1E18;
static class Edge2
{
int node;
long cost;
long next;
Edge2(int a, int c,Long long1) { node = a; cost = long1; next=c;}
}
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 boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | bf600e66e853764f190a9cdbdeb369be | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class B7932 {
static char[][] ip;
// static int[][][] visited;
static int visited[][][][];
static int[][] move = {{1,0},{0,1},{-1,0},{0,-1}};
static int sx,sy,tx,ty,n,m;
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());
}
String nextLine(){
String s= "";
try{
s= br.readLine();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
}
public static boolean bfs(){
Queue<bn> q= new LinkedList<>();
for(int i=0;i<4;i++){
int x= sx + move[i][0];
int y= sy + move[i][1];
if(x>=0 && x<n && y>=0 && y<m && ip[x][y]!='*'){
visited[x][y][i][2]=1;
q.add(new bn(x,y,i,2));
}
}
while(!q.isEmpty()){
bn node = q.poll();
if(node.x==tx && node.y == ty)
return true;
for(int i=0;i<4;i++){
int x= node.x + move[i][0];
int y= node.y + move[i][1];
if(x>=0 && x<n && y>=0 && y<m && ip[x][y]!='*'){
if(i==node.d){
if(visited[x][y][i][node.cnt]==0){
visited[x][y][i][node.cnt]=1;
q.add(new bn(x,y,i,node.cnt));
}
}
else if(i==(node.d+2)%4)
continue;
else if(node.cnt>0){
if(visited[x][y][i][node.cnt-1]==0){
visited[x][y][i][node.cnt-1]=1;
q.add(new bn(x,y,i,node.cnt-1));
}
}
}
}
}
return false;
}
public static void main(String[] args) {
FastReader s = new FastReader();
n = s.nextInt();
m = s.nextInt();
//visited = new int[n][m][4];
visited= new int[n][m][4][3];
ip = new char[n][m];
for(int i=0; i<n; i++){
ip[i]=s.nextLine().toCharArray();
for(int j=0;j<m;j++){
char c = ip[i][j];
if(c=='S'){
sx=i;
sy=j;
}
else if(c=='T'){
tx=i;
ty=j;
}
}
}
if(bfs())
System.out.println("YES");
else
System.out.println("NO");
}
}
class bn{
int x,y,d,cnt;
bn(int x, int y, int d,int cnt){
this.x=x;
this.y=y;
this.d=d;
this.cnt=cnt;
}
} | Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 2ec12dd4ce7378c6582ab879ad596715 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.Scanner;
import javax.net.ssl.HostnameVerifier;
public class B793 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int h = sc.nextInt();
int w = sc.nextInt();
int igorX = 0, igorY = 0, workX = 0, workY = 0;
char[][] map = new char[w][h];
for (int j = 0; j < h; j++) {
String str = sc.next();
for (int i = 0; i < w; i++) {
map[i][j] = str.charAt(i);
if (map[i][j] == 'S') {
igorX = i;
igorY = j;
} else if (map[i][j] == 'T') {
workX = i;
workY = j;
}
}
}
int igorClearL = igorX, igorClearR = igorX, igorClearU = igorY, igorClearD = igorY;
int workClearL = workX, workClearR = workX, workClearU = workY, workClearD = workY;
for (int i = igorX+1; i < w; i++) {
if (map[i][igorY] == '*') {
break;
}
igorClearR++;
}
for (int i = igorX-1; i >= 0; i--) {
if (map[i][igorY] == '*') {
break;
}
igorClearL--;
}
for (int j = igorY+1; j < h; j++) {
if (map[igorX][j] == '*') {
break;
}
igorClearD++;
}
for (int j = igorY-1; j >= 0; j--) {
if (map[igorX][j] == '*') {
break;
}
igorClearU--;
}
for (int i = workX+1; i < w; i++) {
if (map[i][workY] == '*') {
break;
}
workClearR++;
}
for (int i = workX-1; i >= 0; i--) {
if (map[i][workY] == '*') {
break;
}
workClearL--;
}
for (int j = workY+1; j < h; j++) {
if (map[workX][j] == '*') {
break;
}
workClearD++;
}
for (int j = workY-1; j >= 0; j--) {
if (map[workX][j] == '*') {
break;
}
workClearU--;
}
int clearL = workClearL > igorClearL ? workClearL : igorClearL;
int clearR = workClearR > igorClearR ? igorClearR : workClearR;
int clearU = workClearU > igorClearU ? workClearU : igorClearU;
int clearD = workClearD > igorClearD ? igorClearD : workClearD;
for (int i = clearL; i <= clearR; i++) {
int lowY, highY;
if (igorY > workY) {
highY = igorY;
lowY = workY;
} else {
highY = workY;
lowY = igorY;
}
boolean clear = true;
for (int j = lowY; j <= highY; j++) {
if (map[i][j] == '*') {
clear = false;
break;
}
}
if (clear) {
System.out.println("YES");
return;
}
}
for (int j = clearU; j <= clearD; j++) {
int lowX, highX;
if (igorX > workX) {
highX = igorX;
lowX = workX;
} else {
highX = workX;
lowX = igorX;
}
boolean clear = true;
for (int i = lowX; i <= highX; i++) {
if (map[i][j] == '*') {
clear = false;
break;
}
}
if (clear) {
System.out.println("YES");
return;
}
}
System.out.println("NO");
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 774f2f568939e69e2fdd5f0c905b6e66 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main7
{
static int mod=1000000007;
static class Pair
{
int x;
int y;
Pair(int x, int y)
{
this.x=x;
this.y=y;
}
}
public static long pow(long a, long b,long m)
{
long result=1;
while(b>0)
{
if (b % 2 != 0)
{
result=(result*a)%m;
b--;
}
a=(a%mod*a%m)%m;
b /= 2;
}
return result;
}
public static long pow1(long a, long b)
{
long result=1;
while(b>0)
{
if (b % 2 != 0)
{
result=(result*a);
b--;
}
a=(a%mod*a);
b /= 2;
}
return result;
}
public static int[] sort(int[] a)
{
int n=a.length;
ArrayList<Integer> ar=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
ar.add(a[i]);
}
Collections.sort(ar);
for(int i=0;i<n;i++)
{
a[i]=ar.get(i);
}
return a;
}
static int[] tree;
static ArrayList<ArrayList<Integer>> graph;
static public void main(String args[])throws IOException
{
int tt=1;
StringBuilder sb=new StringBuilder();
for(int ttt=1;ttt<=tt;ttt++)
{
int n=i();
int m=i();
char[][] a=new char[n][m];
int startx=0,starty=0,endx=0,endy=0;
for(int i=0;i<n;i++)
{
String s=s();
for(int j=0;j<m;j++)
{
a[i][j]=s.charAt(j);
if(a[i][j]=='S')
{
startx=i;
starty=j;
}
if(a[i][j]=='T')
{
endx=i;
endy=j;
}
}
}
if(startx==endx)
{
int flag=0;
for(int i=Math.min(starty,endy);i<Math.max(endy,starty);i++)
{
if(a[startx][i]=='*')
flag=1;
}
if(flag==0)
pln("YES");
else
pln("NO");
}
else if(starty==endy)
{
int flag=0;
for(int i=Math.min(startx,endx);i<Math.max(endx,startx);i++)
{
if(a[i][starty]=='*')
flag=1;
}
if(flag==0)
pln("YES");
else
pln("NO");
}
else
{
int ans=0;
for(int col=0;col<m;col++)
{
int flag=0;
for(int i=Math.min(startx,endx);i<=Math.max(startx,endx);i++)
{
if(a[i][col]=='*')
{
flag=1;
}
}
if(flag==0)
{
for(int i=Math.min(col,starty);i<=Math.max(col,starty);i++)
{
if(a[startx][i]=='*')
flag=1;
}
if(flag==0)
{
for(int i=Math.min(col,endy);i<=Math.max(col,endy);i++)
{
if(a[endx][i]=='*')
flag=1;
}
if(flag==0)
{
ans=1;
pln("YES");
break;
}
}
}
}
if(ans!=1)
{
for(int row=0;row<n;row++)
{
int flag=0;
for(int i=Math.min(starty,endy);i<=Math.max(starty,endy);i++)
{
if(a[row][i]=='*')
{
flag=1;
}
}
if(flag==0)
{
for(int i=Math.min(row,startx);i<=Math.max(row,startx);i++)
{
if(a[i][starty]=='*')
flag=1;
}
if(flag==0)
{
for(int i=Math.min(row,endx);i<=Math.max(row,endx);i++)
{
if(a[i][endy]=='*')
flag=1;
}
if(flag==0)
{
ans=1;
pln("YES");
break;
}
}
}
}
}
if(ans!=1)
pln("NO");
}
}
System.out.print(sb.toString());
}
/**/
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
public static long l()
{
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value)
{
System.out.println(value);
}
public static int i()
{
return in.Int();
}
public static String s()
{
return in.String();
}
}
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars== -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
} | Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | ab743e38c9ffec9e963e01f478ecfefa | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
import java.text.DecimalFormat;
import java.math.BigInteger;
public class Main{
//static int d=20;
static long mod=1000000007 ;
static ArrayList<ArrayList<Edge>> arr;
// static long[] dp1,dp2;
static int[] a;
static int[] vis,num;
static long max;
static HashSet<String> hs;
//static int flag,ans;
static long max1,max2,ans1;
static long ct=0;
static int flag=0;
static int[] tin,tout,parent,level;
static HashMap<Long,Integer> hm;
static long[] dp1,dp2,dp3,dp4;
public static void main(String[] args) throws IOException {
///long start=System.currentTimeMillis();
boolean online =false;
String fileName = "B-small-attempt0 (3)";
PrintWriter out;
if (online) {
s.init(new FileInputStream(new File(fileName + ".in")));
out= new PrintWriter(new FileWriter(fileName + "out.txt"));
}
else {
s.init(System.in);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//out= new PrintWriter(new FileWriter(fileName + "out.txt"));
}//r,b,y,g
int n=s.ni();
int m=s.ni();
char[][] a=new char[n][m];
for(int i=0;i<n;i++){
String b=s.ns();
for(int j=0;j<m;j++)
a[i][j]=b.charAt(j);
}
int[][][] dp=new int[n][m][4];
int x1,y1,x2,y2;
x1=y1=x2=y2=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
for(int k=0;k<4;k++){
if(a[i][j]=='S'){
y1=i;
x1=j;
dp[i][j][k]=0;
}
else{
dp[i][j][k]=Integer.MAX_VALUE/2;
if(a[i][j]=='T'){
x2=j;
y2=i;
}
}
}
}
}
PriorityQueue<item> pq=new PriorityQueue<item>();
pq.add(new item(x1,y1,0,0));
pq.add(new item(x1,y1,0,1));
pq.add(new item(x1,y1,0,2));
pq.add(new item(x1,y1,0,3));
int flag=0;
int[] dx=new int[]{1,-1,0,0};
int[] dy=new int[]{0,0,-1,1};
while(!pq.isEmpty()){
item z=pq.poll();
int x=z.x;
int y=z.y;
int d=z.dir;
if(x==x2 && y==y2 ){
flag=1;
break;
}
if(z.turn!=dp[y][x][d])
continue;
for(int i=0;i<4;i++){
int u=x+dx[i];
int v=y+dy[i];
if(u<0 || u>=m || v<0 || v>=n)
continue;
if(a[v][u]=='*')
continue;
if(i==d && dp[v][u][i]>z.turn){
dp[v][u][i]=z.turn;
pq.add(new item(u,v,z.turn,i));
}
else{
if(dp[v][u][i]<=z.turn+1)
continue;
if(z.turn>=2)
continue;
dp[v][u][i]=z.turn+1;
pq.add(new item(u,v,z.turn+1,i));
}
}
}
if(flag==1)
out.println("YES");
else
out.println("NO");
out.close();
}
public static int gcd(int a, int b){
if (a == 0) return b;
return gcd(b % a, a);
}
public static void cfs(ArrayList<HashSet<Integer>> arr,int c,int p,int g,int[] vis){
vis[c]=1;
if(g!=-1){
if(!arr.get(c).contains(g)){
flag=1;
return;
}
}
for(int x:arr.get(c)){
if(x!=p && x!=g && vis[x]==0 ){
cfs(arr,x,c,p,vis);
}
}
}
// public static void dfs(int u,int p){
// // if(p>=0)
// // tin[u]=tout[u]=tt++;
// // if(p>=0)
// // level[u]=level[p]+1;
// // parent[u]=p;
// // for(int x:arr.get(u)){
// // if(x!=p){
// // dfs(x,u);
// // tout[u]=Math.max(tout[u],tout[x]);
// // }
// // }
// //
//
//
// }
public static int lca(int[][] p,int a,int b){
if(level[a]<level[b]){
int x=a;
a=b;
b=x;
}
int log=p[0].length;
for(int i=log-1;i>=0;i--){
if(1<<i<=level[a]-level[b]){
a=p[a][i];
}
}
if(a==b)
return a;
for(int i=log-1;i>=0;i--){
if(p[a][i]!=p[b][i]){
a=p[a][i];
b=p[b][i];
}
}
return p[a][0];
}
public static int[][] par(int[] parent){
int n=arr.size();
int[][] p=new int[n][17];
for(int i=0;i<n;i++)
p[i][0]=parent[i];
for(int k=1;k<17;k++){
for(int i=0;i<n;i++){
if(p[i][k-1]>-1)
p[i][k]=p[p[i][k-1]][k-1];
else
p[i][k]=-1;
}
}
return p;
}
static class Edge {
int from;
int to;
int cost;
public Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.cost= weight;
}
}
static class Node {
int start;
int end;
int cost;
int updated;
Node[] nodes;
public Node(int start, int end) {
this.start = start;
this.end = end;
if (start < end) {
int[] pos = {start, (start + end) / 2, end};
nodes = new Node[2];
for (int i = 0; i < 2; i++) {
nodes[i] = new Node(pos[i] + i, pos[i + 1]);
}
}
}
public void update(int queryStart, int queryEnd, int value) {
if (queryEnd < start || end < queryStart) {
return;
}
if (queryStart <= start && end <= queryEnd) {
cost += value;
updated += value;
return;
}
propagate();
for (Node node: nodes) {
node.update(queryStart, queryEnd, value);
}
}
public int query(int pos) {
if (pos < start || end < pos) {
return 0;
}
if (start == end) {
return cost;
}
propagate();
int ans = 0;
for (Node node: nodes) {
ans = Math.max(ans, node.query(pos));
}
return ans;
}
public void propagate() {
if (updated != 0 && start < end) {
for (Node node: nodes) {
node.cost += updated;
node.updated += updated;
}
updated = 0;
}
}
}
public static double nthroot(int n, double A) {
return nthroot(n, A, 0.00000000000001);
}
public static double nthroot(int n, double A, double p) {
if(A < 0) {
System.err.println("A < 0");// we handle only real positive numbers
return -1;
} else if(A == 0) {
return 0;
}
double x_prev = A;
double x = A / n; // starting "guessed" value...
while(Math.abs(x - x_prev) > p) {
x_prev = x;
x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n;
}
return x;
}
static class item implements Comparable<item> {
int x,y,turn,dir;
public item(int a,int b,int c,int d){
x=a;
y=b;
turn =c;
dir=d;
}
public int compareTo(item o){
return turn-o.turn;
}
}
public static void dfs2(int c,int p,int[] a){
//System.out.println(c+" "+p);
}
//public static void dfs(int x,int[] vis,Stack<Integer> st){
// vis[x]=1;
// ArrayList<Integer> arr2=arr.get(x);
// Collections.sort(arr2);
// for(int i=arr2.size()-1;i>=0;i--){
// int z=arr2.get(i);
// if(vis[z]==0)
// dfs(z,vis,st);
// }
// st.push(x);
//
//}
public static long gcd(long a, long b){
if (a == 0) return b;
return gcd(b % a, a);
}
public static boolean check(long x){
if(x%4==0 || x%7==0 || x%11==0)
return true;
if(x<4 || x<7 || x<11)
return false;
if(x%2==0){
return check(x/2);
}
else
return check(x/2) && check((x+1)/2);
}
public static int angle(int x1,int x2,int x3,int y1,int y2,int y3){
long val=(y2-y1)*1L*(x3-x2)-(y3-y2)*1L*(x2-x1);
if(val<0)
return 1;
else if(val>0)
return -1;
else
return 0;
}
static class BIT{
int N;
long tree[];
BIT(int N){
this.N = N;
tree = new long[N + 1];
}
void update(int idx,long val){
while(idx <= N){
tree[idx]+=val;
idx += (idx & -idx);
}
}
long query(int l,int r){
if(l == 1)
return read(r);
else
return read(r) - read(l-1);
}
long read(int idx){
long sum = 0;
while(idx > 0){
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}
}
public static boolean pal(String a){
int i=0;
int j=a.length()-1;
while(i<j){
if(a.charAt(i)!=a.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
public static long find(long n,long k){
if(n==2){
if(k==1 || k==3)
return 1;
else
return 2;
}
long t=pow2(2,n,mod)-1;
long z=(t+1)/2;
if(k==z)
return n;
if(k<z)
return find(n-1,k);
else
return find(n-1,k-z);
}
public static long pow2(long a,long b,long mod){
long ans=1;
// long z=b;
while(b>0){
if(b%2==1)
ans=(a*ans)%mod;
a=(a*a)%mod;
b/=2;
}
return ans;
}
public static long pow3(long a,long b){
long ans=1;
// long z=b;
while(b>0){
if(b%2==1)
ans=(a*ans);
a=(a*a);
b/=2;
}
return ans;
}
public static long fib(long n){
long[][] f=new long[][]{{1L,1L},{1L,0}};
if(n==0)
return 0;
f=arrpow(f,n-1);
return f[0][0];
}
public static long[][] arrpow(long[][] a,long b){
int n=a.length;
// long z=b;
long[][] ans=new long[n][n];
for(int i=0;i<n;i++)
ans[i][i]=1L;
while(b>0){
if(b%2==1)
ans=mul(a,ans);
a=mul(a,a);
b/=2;
}
return ans;
}
public static long[][] mul(long[][] a,long[][] b){
int n=a.length;
int m=b[0].length;
long[][] ans=new long[n][m];
if(n==2 && m==2 && b.length==2){
ans[0][0]=((a[0][0]*b[0][0])%mod+(a[0][1]*b[1][0]))%mod;
ans[0][1]=((a[0][0]*b[0][1])%mod+(a[0][1]*b[1][1]))%mod;
ans[1][0]=((a[1][0]*b[0][0])%mod+(a[1][1]*b[1][0]))%mod;
ans[1][1]=((a[1][1]*b[1][1])%mod+(a[1][0]*b[0][1]))%mod;
return ans;
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
for(int k=0;k<b.length;k++){
ans[i][j]=(ans[i][j]+(a[i][k]*b[k][j])%mod)%mod;
}
}
}
return ans;
}
static class name implements Comparable<name> {
long l,b,h;
public name(long x,long y,long z){
{
l=x;
b=y;
}
h=z;
}
public int compareTo(name o){
return -(int)(l*b-o.l*o.b);
}
}
public static class s {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String ns() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int ni() throws IOException {
return Integer.parseInt( ns() );
}
static double nd() throws IOException {
return Double.parseDouble( ns() );
}
static long nl() throws IOException {
return Long.parseLong( ns() );
}
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 359689cb27d76abe2d44124b75ed2631 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | //author: Ala Abid
import java.io.*;
import java.util.*;
public class B {
static char[][] grid;
static int m,n,si,sj,ti,tj;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n= Integer.parseInt(st.nextToken());
m= Integer.parseInt(st.nextToken());
grid = new char[n][m];
for(int i=0;i<n;i++){
grid[i]=br.readLine().toCharArray();
}
ti=0;tj=0;si=0;sj=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]=='S'){
si=i;
sj=j;
}
else if(grid[i][j]=='T'){
ti=i;
tj=j;
}
}
}
getPath(ti,tj,0,'u');
getPath(ti,tj,0,'d');
getPath(ti,tj,0,'l');
getPath(ti,tj,0,'r');
System.out.println("NO");
}
static void getPath(int x, int y, int turns, char dir){
if(turns==3) return;
if(turns==2 && (dir=='u' || dir=='d') && y!=sj) return;
if(turns==2 && (dir=='l' || dir=='r') && x!=si) return;
if(x==si && y==sj){
System.out.println("YES");
System.exit(0);
}
if(dir=='u'){
if(x!=0 && grid[x-1][y]!='*'){
getPath(x-1,y,turns,'u');
}
if(y!=0 && grid[x][y-1]!='*'){
getPath(x,y-1,turns+1,'l');
}
if(y!=m-1 && grid[x][y+1]!='*'){
getPath(x,y+1,turns+1,'r');
}
}
else if(dir=='d'){
if(x!=n-1 && grid[x+1][y]!='*'){
getPath(x+1,y,turns,'d');
}
if(y!=0 && grid[x][y-1]!='*'){
getPath(x,y-1,turns+1,'l');
}
if(y!=m-1 && grid[x][y+1]!='*'){
getPath(x,y+1,turns+1,'r');
}
}
else if(dir=='l'){
if(x!=n-1 && grid[x+1][y]!='*'){
getPath(x+1,y,turns+1,'d');
}
if(y!=0 && grid[x][y-1]!='*'){
getPath(x,y-1,turns,'l');
}
if(x!=0 && grid[x-1][y]!='*'){
getPath(x-1,y,turns+1,'u');
}
}
else if(dir=='r'){
if(x!=0 && grid[x-1][y]!='*'){
getPath(x-1,y,turns+1,'u');
}
if(x!=n-1 && grid[x+1][y]!='*'){
getPath(x+1,y,turns+1,'d');
}
if(y!=m-1 && grid[x][y+1]!='*'){
getPath(x,y+1,turns,'r');
}
}
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | acbfd6d4a9c62983f42a0b87b8b726e9 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes |
import java.util.*;
import java.io.*;
public class IgorWayToWork {
String ans = "NO";
boolean[][][] visited;
int startx, starty, endx, endy;
int n, m;
public void dfs(int[][] board, int x, int y, int dir, int turns) {
// dir == 0 -> starting, no direction
// dir == 1 -> vertical
// dir == 2 -> horizontal
if (x == endx && y == endy) {
ans = "YES";
}
if (ans.equals("YES")) {
return;
}
visited[x][y][turns] = true;
int[] chx = {x - 1, x, x + 1, x};
int[] chy = {y, y - 1, y, y + 1};
for (int i = 0; i < 4; ++i) {
if (ans.equals("YES")) {
return;
}
int tmpx = chx[i];
int tmpy = chy[i];
// System.out.printf("x: %d, y: %d, turns: %d\n", x, y, turns);
// System.out.printf("tmpx: %d, tmpy: %d\n", tmpx, tmpy);
if (tmpx < 0 || tmpx >= n || tmpy < 0 || tmpy >= m) {
continue;
}
if (board[tmpx][tmpy] == 1 && !visited[tmpx][tmpy][turns]) {
if (dir == 1 && tmpy != y) {
if (turns < 2) dfs(board, tmpx, tmpy, 2, turns + 1);
} else if (dir == 2 && tmpx != x) {
if (turns < 2) dfs(board, tmpx, tmpy, 1, turns + 1);
} else {
int tmpdir = dir;
if (dir == 0) tmpdir = (tmpy != y) ? 2 : 1;
dfs(board, tmpx, tmpy, tmpdir, turns);
}
}
}
}
public void run(BufferedReader br, PrintWriter pw) throws IOException {
StringTokenizer st;
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
int[][] board = new int[n][m];
for (int i = 0; i < n; ++i) {
String s = br.readLine();
for (int j = 0; j < m; ++j) {
char c = s.charAt(j);
if (c != '*') {
board[i][j] = 1;
if (c == 'S') {
startx = i;
starty = j;
}
if (c == 'T') {
endx = i;
endy = j;
}
}
}
}
visited = new boolean[n][m][3];
dfs(board, startx, starty, 0, 0);
// util.print2d(board, n, m);
pw.println(ans);
}
public static void main(String[] args) throws IOException {
// new IgorWayToWork().runFileIO("AbandonedSettlement");
new IgorWayToWork().runStdIO();
}
public void runFileIO(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename + ".in"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(filename + ".out")));
run(br, pw);
pw.close();
}
public void runStdIO() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
run(br, pw);
pw.close();
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 3738fb81a551fdf20b91f74e89ed1359 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* 作者:张宇翔 创建日期:2017年4月23日 下午3:58:22 描述:
*/
public class test {
private static final int Max = (int) (1e3 + 10);
private static int n;
private static int m;
private static String[] s;
private static int[][] dir = new int[][] { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
private static int startx, starty, endx, endy;
private static int vis[][][];
private static boolean ok;
public static void main(String[] args) throws Exception {
Init();
BFS();
if (!ok) {
System.out.println("NO");
}
}
private static void Init() throws Exception {
SC cin = new SC(System.in);
n = cin.nextInt();
m = cin.nextInt();
vis = new int[Max][Max][10];
s = new String[Max];
ok = false;
for (int i = 0; i < n; i++) {
s[i] = cin.next();
for (int j = 0; j < m; j++) {
if (s[i].charAt(j) == 'S') {
startx = i;
starty = j;
}
if (s[i].charAt(j) == 'T') {
endx = i;
endy = j;
}
}
}
for(int i=0;i<Max;i++){
for(int j=0;j<Max;j++){
for(int k=0;k<4;k++){
vis[i][j][k]=Integer.MAX_VALUE;
}
}
}
// System.out.println(startx+" "+starty);
// System.out.println(endx+" "+endy);
}
private static void BFS() {
Queue<Node> queue = new LinkedList<Node>();
Node node = new Node(startx, starty, 0, 0, 0);
queue.add(node);
while (!queue.isEmpty()) {
Node pre = queue.poll();
if (pre.getX() == endx && pre.getY() == endy) {
ok = true;
// System.out.println("转弯:" + pre.getTurn());
// System.out.println("步数:" + pre.step);
System.out.println("YES");
return;
}
for (int i = 0; i < 4; i++) {
Node node2 = new Node();
node2.setX(pre.getX() + dir[i][0]);
node2.setY(pre.getY() + dir[i][1]);
node2.setStep(pre.getStep() + 1);
if (node2.getX() - pre.getX() == 1) {
node2.setDirection(2);
if (pre.getDirection() != 2 && pre.getDirection() != 0 && pre.getDirection() != 1) {
node2.setTurn(pre.getTurn() + 1);
} else {
node2.setTurn(pre.getTurn());
}
} else if (node2.getX() - pre.getX() == -1) {
node2.setDirection(1);
if (pre.getDirection() != 1 && pre.getDirection() != 0 && pre.getDirection() != 2) {
node2.setTurn(pre.getTurn() + 1);
} else {
node2.setTurn(pre.getTurn());
}
} else if (node2.getY() - pre.getY() == 1) {
node2.setDirection(4);
if (pre.getDirection() != 4 && pre.getDirection() != 0 && pre.getDirection() != 3) {
node2.setTurn(pre.getTurn() + 1);
} else {
node2.setTurn(pre.getTurn());
}
} else if (node2.getY() - pre.getY() == -1) {
node2.setDirection(3);
if (pre.getDirection() != 3 && pre.getDirection() != 0 && pre.getDirection() != 4) {
node2.setTurn(pre.getTurn() + 1);
} else {
node2.setTurn(pre.getTurn());
}
}
if (check(node2.getX(), node2.getY(), node2.getTurn())) {
if(vis[node2.getX()][node2.getY()][i]>node2.getTurn()){
vis[node2.getX()][node2.getY()][i] = node2.getTurn();
queue.add(node2);
}
}
}
}
}
// 合法返回true,不合法返回false
private static boolean check(int x, int y, int turn) {
if (x >= 0 && x < n && y >= 0 && y < m && (turn <= 2) && (s[x].charAt(y) != '*'))
return true;
return false;
}
static class Node {
int x;// x轴坐标
int y;// y轴坐标
int step;// 步数
int turn;// 转弯的数量
int direction;// 方向 0:表示起始方向,1表示向左,2表示向右,3表示向上,4表示向下
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public int getTurn() {
return turn;
}
public void setTurn(int turn) {
this.turn = turn;
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public Node(int x, int y, int step, int turn, int direction) {
super();
this.x = x;
this.y = y;
this.step = step;
this.turn = turn;
this.direction = direction;
}
public Node() {
super();
}
}
static class SC {
BufferedReader br;
StringTokenizer st;
SC(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 65cc726e25318d621e1a1ce11ab87533 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes |
import java.util.Scanner;
public class solution {
static String[][] matrix;
static boolean[][][][] isvisited;
static int m;
static int n;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
m = input.nextInt();
n = input.nextInt();
matrix = new String[m][n];
isvisited = new boolean[4][3][m][n];
int startI = 0;
int startJ = 0;
for (int i = 0; i < m; i++) {
String nStr = input.next();
for (int j = 0; j < nStr.length(); j++) {
matrix[i][j] = nStr.charAt(j) + "";
if (matrix[i][j].equals("S")) {
startI = i;
startJ = j;
}
}
}
// dfs
int[][] dir = { { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 } };
boolean result = dfs(startI, startJ, 2, dir, 0) ||
dfs(startI, startJ, 2, dir, 3);
if (result == true)
System.out.println("YES");
else
System.out.println("NO");
}
public static boolean dfs(int x, int y, int turn, int[][] dir, int dirI) {
if (x >= m || y >= n || x < 0 || y < 0 || turn < 0
|| matrix[x][y].equals("*")
|| isvisited[dirI][turn][x][y] == true) {
return false;
}
if (matrix[x][y].equals("T")) {
return true;
}
isvisited[dirI][turn][x][y] = true;
boolean ok = false;
for (int i = 0; i < 4; i++) {
// System.out.println(i/2 +" " + dirI/2);
if ((i / 2) != (dirI / 2)) {
ok |= dfs(x + dir[i][0], y + dir[i][1], turn - 1, dir, i);
} else {
ok |= dfs(x + dir[i][0], y + dir[i][1], turn, dir, i);
}
}
return ok;
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 4767597ee1e49762dd1d72c49aabf9fa | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes |
import java.util.Scanner;
public class ProblemB {
static int endX;
static int endY;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int height=sc.nextInt();
int width=sc.nextInt();
char[][] board=new char[height][width];
int startX=0;
int startY=0;
endX=0;
endY=0;
for(int i=0;i<height;i++){
String line=sc.next();
for(int j=0;j<width;j++){
board[i][j]=line.charAt(j);
if(board[i][j]=='S'){
startX=i;
startY=j;
}else if(board[i][j]=='T'){
endX=i;
endY=j;
}
}
}
if(backtracking(board,startX+1,startY,2,1,0)||backtracking(board,startX,startY+1,2,0,1)||backtracking(board,startX-1,startY,2,-1,0)||backtracking(board,startX,startY-1,2,0,-1)){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
public static boolean backtracking(char[][] board, int x, int y, int turns,int directionX, int directionY){
if(x==board.length||x<0||y<0||y==board[0].length) return false;
if(board[x][y]=='T') return true;
if(board[x][y]=='*') return false;
if(turns>0){
boolean valid=false;
if(directionX==1&&directionY==0){
valid=valid||backtracking(board,x+1,y+0,turns,1,0);
}else{
valid=valid||backtracking(board,x+1,y+0,turns-1,1,0);
}
if(directionX==0&&directionY==1){
valid=valid||backtracking(board,x+0,y+1,turns,0,1);
}else{
valid=valid||backtracking(board,x+0,y+1,turns-1,0,1);
}
if(directionX==-1&&directionY==0){
valid=valid||backtracking(board,x-1,y+0,turns,-1,0);
}else{
valid=valid||backtracking(board,x-1,y+0,turns-1,-1,0);
}
if(directionX==0&&directionY==-1){
valid=valid||backtracking(board,x,y-1,turns,0,-1);
}else{
valid=valid||backtracking(board,x,y-1,turns-1,0,-1);
}
return valid;
}else{
if(directionX==1&&endY==y&&endX>x){
boolean valid=true;
for(int i=x;i<endX;i++){
if(board[i][y]=='*'){
valid=false;
break;
}
}
return valid;
}
if(directionX==-1&&endY==y&&endX<x){
boolean valid=true;
for(int i=x;i>endX;i--){
if(board[i][y]=='*'){
valid=false;
break;
}
}
return valid;
}
if(directionY==1&&endX==x&&endY>y){
boolean valid=true;
for(int i=y;i<endY;i++){
if(board[x][i]=='*'){
valid=false;
break;
}
}
return valid;
}
if(directionY==-1&&endX==x&&endY<y){
boolean valid=true;
for(int i=y;i>endY;i--){
if(board[x][i]=='*'){
valid=false;
break;
}
}
return valid;
}
return false;
}
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 3809b78b31eae0cbce53aa1fbb7291e5 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import javafx.scene.layout.Priority;
import java.io.*;
import java.net.Inet4Address;
import java.util.*;
import java.lang.*;
import java.util.HashMap;
import java.util.PriorityQueue;
public class templ implements Runnable {
public class pair implements Comparable
{
int f,s;
pair(int f,int s)
{
this.f=f;
this.s=s;
}
public boolean equals(Object o)
{
pair ob=(pair)o;
int ff,ss;
if(o!=null)
{
ff=ob.f;
ss=ob.s;
if((ff==this.f)&&(ss==this.s))
return true;
}
return false;
}
public int hashCode()
{
return (this.f+" "+this.s).hashCode();
}
public int compareTo(Object o)
{
pair pr=(pair)o;
if(s>pr.s)
return 1;
else
return -1;
}
}
int a[][];
int memo[][][][];
int x=-1,y=-1,n,m,x1=-1,y1=-1;
int solve(int i,int j,int d,int turn)
{
if(i<0||i>=n||j<0||j>=m)
return 10;
if(a[i][j]==1)
return 10;
if(turn>2)
return 10;
if(a[i][j]==4)
return 0;
if(memo[i][j][d][turn]!=-1)
return memo[i][j][d][turn];
if(d==0)
{
memo[i][j][d][turn]=solve(i-1,j,0,turn);
int q=1+Math.min(solve(i,j-1,3,turn+1),Math.min(10,solve(i,j+1,2,turn+1)));
memo[i][j][d][turn]=Math.min(memo[i][j][d][turn],q);
}
if(d==1)
{
memo[i][j][d][turn]=solve(i+1,j,1,turn);
int q=1+Math.min(solve(i,j-1,3,turn+1),Math.min(10,solve(i,j+1,2,turn+1)));
memo[i][j][d][turn]=Math.min(memo[i][j][d][turn],q);
}
if(d==2)
{
memo[i][j][d][turn]=solve(i,j+1,2,turn);
int q=1+Math.min(10,Math.min(solve(i-1,j,0,turn+1),solve(i+1,j,1,turn+1)));
memo[i][j][d][turn]=Math.min(memo[i][j][d][turn],q);
}
if(d==3)
{
memo[i][j][d][turn]=solve(i,j-1,3,turn);
int q=1+Math.min(solve(i+1,j,1,turn+1),Math.min(solve(i-1,j,0,turn+1),10));
memo[i][j][d][turn]=Math.min(memo[i][j][d][turn],q);
}
return memo[i][j][d][turn];
}
public static void main(String args[])throws Exception
{
new Thread(null,new templ(),"templ",1<<26).start();
}
public void run() {
try {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
n=in.ni();
m=in.ni();
a=new int[n][m];
memo=new int[n][m][4][3];
for(int i=0;i<n;i++)
{
String s=in.nextLine();
for(int j=0;j<m;j++)
{
char c=s.charAt(j);
if(c=='.')
a[i][j]=0;
if(c=='*')
a[i][j]=1;
if(c=='S')
{
x=i;
y=j;
a[i][j] = 3;
}
if(c=='T')
{
x1=i;
y1=j;
a[i][j] = 4;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
for(int k=0;k<4;k++)
{
for(int kk=0;kk<3;kk++)
memo[i][j][k][kk] = -1;
}
}
}
//int ans=0;
//System.out.println("hi");
int ans=Math.min(solve(x+1,y,1,0),Math.min(solve(x,y+1,2,0),Math.min(solve(x,y-1,3,0),solve(x-1,y,0,0))));
//out.println(ans);
//out.println(ans);
//out.println(solve(x,y-1,3,0));
if(ans<=2)
out.println("YES");
else
out.println("NO");
out.close();
}
catch(Exception e){
return;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(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 ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} 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] = ni();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String 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;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 4de9ee3cf13af6d04536890939ecbf15 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.System;;
public class Luck{
public static InputReader sc;
public static PrintWriter out;
public static final int MOD = (int) (1e9 + 7);
static int[] rMove={-1,0,1,0};
static int[] cMove={0,1,0,-1};
static int N=(int)1e3+3;
static int n;
static int m;
static int sRow;
static int sCol;
static int eRow;
static int eCol;
static char[][] A;
static int[][][] dp;
static Node[] que;
static int[] direction;
static int q1,qr;
static void relax(int row,int col,int dir,int turns){
if(dp[row][col][dir]>turns){
dp[row][col][dir]=turns;
que[qr]=new Node(row,col);
direction[qr]=dir;
qr+=1;
}
}
public static void main(String[] args){
sc=new InputReader(System.in);
out=new PrintWriter(System.out);
n=sc.nextInt();
m=sc.nextInt();
A=new char[n][m];
dp=new int[N][N][4];
que=new Node[N*N*10];
direction=new int[que.length];
for(int i=0;i<n;i++){
A[i]=sc.readString().toCharArray();
for(int j=0;j<A[i].length;j++){
Arrays.fill(dp[i][j], Integer.MAX_VALUE);
if(A[i][j]=='S'){
sRow=i;
sCol=j;
}
if(A[i][j]=='T'){
eRow=i;
eCol=j;
}
}
}
q1=0;
qr=0;
for(int i=0;i<4;i++){
relax(sRow,sCol,i,0);
}
while(q1<qr){
int row=que[q1].u;
int col=que[q1].v;
int d=direction[q1];
int turns=dp[row][col][d];
for(int i=0;i<4;i++){
if(isSafe(row+rMove[i],col+cMove[i],turns)){
if(i!=d){
relax(row+rMove[i],col+cMove[i],i,turns+1);
}
else{
relax(row+rMove[i],col+cMove[i],i,turns);
}
}
}
q1+=1;
}
int ans=Integer.MAX_VALUE;
for(int i=0;i<4;i++){
if(dp[eRow][eCol][i]<ans){
ans=dp[eRow][eCol][i];
}
}
if(ans<=2){
out.println("YES");
}
else{
out.println("NO");
}
out.close();
}
static boolean isSafe(int row,int col,int turns){
return turns<=2 && row>=0 && row<n && col>=0 && col<m && (A[row][col]=='.' ||A[row][col]=='T');
}
static int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
static int lcm(int a,int b){
int g;
if(a<b){
g=gcd(b,a);
}
else{
g=gcd(a,b);
}
return (a*b)/g;
}
static boolean isPrime(int n){
if (n == 2)
return true;
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
static void shuffle(int[] A){
for(int i=A.length-1;i>0;i--){
int j=(int)(Math.random()*(i+1));
int temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}
public static class Node implements Comparable<Node>{
int u;
int v;
public Node(){
;
}
public Node (int u, int v) {
this.u = u;
this.v = v;
}
public void print() {
out.println(v + " " + u + " ");
}
public int compareTo(Node n1){
return this.u-n1.u;
}
}
public static BigInteger pow(BigInteger base, BigInteger exp) {
if(exp.equals(new BigInteger(String.valueOf(0)))){
return new BigInteger(String.valueOf(1));
}
if(exp.equals(new BigInteger(String.valueOf(1))))
return base;
BigInteger temp=exp.divide(new BigInteger(String.valueOf(2)));
BigInteger val = pow(base, temp);
BigInteger result = val.multiply(val);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
BigInteger AND=exp.and(new BigInteger(String.valueOf(1)));
if(AND.equals(new BigInteger(String.valueOf(1)))){
result = result.multiply(base);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
}
return result;
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 3d3eba84669c0006f00a7309aaf01b09 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.*;
import java.io.*;
public class R793B2 {
FastScanner in;
PrintWriter out;
int x, y, n, m;
char[][]a;
int[][]aa;
void solve() {
n=in.nextInt();
m=in.nextInt();
a=new char[n][m];
aa=new int[n][m];
for(int i=0; i<n; i++) {
String s=in.next();
for(int j=0; j<m; j++) {
a[i][j] = s.charAt(j);
aa[i][j]=3;
if (a[i][j]=='S') {
x=j;
y=i;
}
}
}
Queue<Pair> b=new LinkedList<>();
b.add(new Pair(x, y, 0, 0));
int dd, cc;
while(!b.isEmpty()) {
Pair p=b.remove();
if (p.d!=3 && p.x+1<m && a[p.y][p.x+1]!='*') {
cc=(p.d==0 || p.d==1)?p.c:p.c+1;
if (cc<3 && a[p.y][p.x + 1] == 'T') {
System.out.println("YES");
return;
}
if (cc<3 && aa[p.y][p.x+1]>=cc) {
b.add(new Pair(p.x + 1, p.y, cc, 1));
aa[p.y][p.x+1]=cc;
}
}
if (p.d!=4 && p.y+1<n && a[p.y+1][p.x]!='*') {
cc=(p.d==0 || p.d==2)?p.c:p.c+1;
if (cc<3 && a[p.y+1][p.x] == 'T') {
System.out.println("YES");
return;
}
if (cc<3 && aa[p.y+1][p.x]>=cc) {
b.add(new Pair(p.x, p.y + 1, cc, 2));
aa[p.y+1][p.x]=cc;
}
}
if (p.d!=1 && p.x>0 && a[p.y][p.x-1]!='*') {
cc=(p.d==0 || p.d==3)?p.c:p.c+1;
if (cc<3 && a[p.y][p.x - 1] == 'T') {
System.out.println("YES");
return;
}
if (cc<3 && aa[p.y][p.x-1]>=cc) {
b.add(new Pair(p.x - 1, p.y, cc, 3));
aa[p.y][p.x-1]=cc;
}
}
if (p.d!=2 && p.y>0 && a[p.y-1][p.x]!='*') {
cc=(p.d==0 || p.d==4)?p.c:p.c+1;
if (cc<3 && a[p.y-1][p.x] == 'T') {
System.out.println("YES");
return;
}
if (cc<3 && aa[p.y-1][p.x]>=cc) {
b.add(new Pair(p.x, p.y - 1, cc, 4));
aa[p.y-1][p.x]=cc;
}
}
}
System.out.println("NO");
}
void run() {
try {
in = new FastScanner(new File("CF.in"));
out = new PrintWriter(new File("CF.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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());
}
}
class Pair {
public int x;
public int y;
public int c;
public int d;
public Pair(int x, int y, int c, int d) {
this.x = x;
this.y = y;
this.d=d;
this.c=c;
}
}
public static void main(String[] args) {
new R793B2().runIO();
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 91890ee001544565158f8f6868a138d5 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class B extends PrintWriter {
void run() {
int n = nextInt(), m = nextInt();
char[][] map = new char[n][];
for (int i = 0; i < n; i++) {
map[i] = next().toCharArray();
}
int[] dx = { +1, +0, -1, -0 };
int[] dy = { +0, +1, -0, -1 };
int k = 4;
int[][][] cnt = new int[k][n][m];
final int inf = 1 << 22;
int[] qr = new int[inf], qx = new int[inf], qy = new int[inf];
int h = 0, t = 0;
for (int r = 0; r < k; r++) {
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++) {
if (map[x][y] == 'S') {
qr[t] = r;
qx[t] = x;
qy[t] = y;
++t;
} else {
cnt[r][x][y] = inf;
}
}
}
}
while (h != t) {
int x = qx[h];
int y = qy[h];
int r = qr[h];
int c = cnt[r][x][y];
h = (h + 1) % inf;
{
int tx = x + dx[r];
int ty = y + dy[r];
if (0 <= tx && tx < n) {
if (0 <= ty && ty < m) {
if (map[x][y] != '*') {
if (c < cnt[r][tx][ty]) {
cnt[r][tx][ty] = c;
h = (h - 1 + inf) % inf;
qr[h] = r;
qx[h] = tx;
qy[h] = ty;
}
}
}
}
}
for (int tr = 0; tr < k; tr++) {
int tc = c + min(abs(r - tr), k - abs(r - tr));
if (tc < cnt[tr][x][y]) {
cnt[tr][x][y] = tc;
qr[t] = tr;
qx[t] = x;
qy[t] = y;
t = (t + 1) % inf;
}
}
}
int ans = inf;
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++) {
if (map[x][y] == 'T') {
for (int r = 0; r < k; r++) {
ans = min(ans, cnt[r][x][y]);
}
}
}
}
if (ans <= 2) {
println("YES");
} else {
println("NO");
}
}
void skip() {
while (hasNext()) {
next();
}
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
String next() {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
int[] nextArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException err) {
return null;
}
}
public B(OutputStream outputStream) {
super(outputStream);
}
static BufferedReader reader;
static StringTokenizer tokenizer = new StringTokenizer("");
static Random rnd = new Random();
static boolean OJ;
public static void main(String[] args) throws IOException {
OJ = System.getProperty("ONLINE_JUDGE") != null;
B solution = new B(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(B.class.getName() + ".txt")));
long timeout = System.currentTimeMillis();
while (solution.hasNext()) {
solution.run();
solution.println();
solution.println("----------------------------------");
}
solution.println("time: " + (System.currentTimeMillis() - timeout));
}
solution.close();
reader.close();
}
} | Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | a91cf7789597dd2222c3cd56d9f6a055 | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
import java.text.*;
public class A{
static class Node{
int x;
int y;
int cnt;
int x1;
int y1;
public Node(int x,int y,int cnt,int x1,int y1) {
this.x=x;
this.y=y;
this.cnt=cnt;
this.x1=x1;
this.y1=y1;
}
}
//public static PrintWriter pw;
public static PrintWriter pw=new PrintWriter(System.out);
public static void solve() throws IOException{
// pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in"));
FastReader sc=new FastReader();
int n=sc.I();
int m=sc.I();
s=new char[n][m];
int xi=-1,yi=-1,xf=-1,yf=-1;
for(int i=0;i<n;i++) {
s[i]=sc.next().toCharArray();
for(int j=0;j<m;j++) { if(s[i][j]=='S') {
xi=i; yi=j;
}else if(s[i][j]=='T') {
xf=i; yf=j;
}
}
}
vis=new boolean[n][m];
bfs(xi,yi,n,m);
if(vis[xf][yf] && dist[xf][yf]<=2) pw.println("YES"); else pw.println("NO");
pw.close();
}
static int dx[]= {-1,0,1,0};
static int dy[]= {0,1,0,-1};
static boolean vis[][];
static char s[][];
static int dist[][];
static int disc[][];
static boolean isValid(int x,int y,int n,int m) {
return(x>=0 && x<n && y>=0 && y<m && s[x][y]!='*' );
}
static void bfs(int xi,int yi,int n,int m) {
Queue<Node> q=new LinkedList<>();
q.offer(new Node(xi,yi,0,-1,-1));
dist=new int[n][m];
for(int i=0;i<n;i++) Arrays.fill(dist[i],1000000);
dist[xi][yi]=0;
disc=new int[n][m];
for(int i=0;i<n;i++) Arrays.fill(disc[i], -1);
disc[xi][yi]=0;
while(!q.isEmpty()) {
Node t=q.poll();
if(vis[t.x][t.y]) continue;
vis[t.x][t.y]=true;
// pw.println(t.x+" "+t.y+" "+dist[t.x][t.y]);
for(int i=0;i<4;i++) {
if(isValid(t.x+dx[i],t.y+dy[i],n,m)) {int cnt=Integer.MAX_VALUE;
for(int j=0;j<4;j++) {
if(i!=j && isValid(t.x+dx[j],t.y+dy[j],n,m) && disc[t.x+dx[j]][t.y+dy[j]]!=-1 && disc[t.x+dx[j]][t.y+dy[j]]<disc[t.x][t.y] ) {
if(dx[j]!=dx[i] && dy[j]!=dy[i]) cnt=Math.min(cnt, 1);
else cnt=Math.min(cnt,0);
}
}
if(cnt==Integer.MAX_VALUE) cnt=0;
//if(t.x+dx[i]==1 && t.y+dy[i]==1) pw.println(cnt);
if(dist[t.x][t.y]+cnt<dist[t.x+dx[i]][t.y+dy[i]]) {
dist[t.x+dx[i]][t.y+dy[i]]=cnt+dist[t.x][t.y];
disc[t.x+dx[i]][t.y+dy[i]]=1+disc[t.x][t.y];
q.offer(new Node(t.x+dx[i],t.y+dy[i],dist[t.x+dx[i]][t.y+dy[i]],t.x,t.y));
}
}
}
}
}
public static void main(String[] args) {
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static long M=(long)Math.pow(10,9)+7;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException{
//br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in"));
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int I(){ return Integer.parseInt(next()); }
long L(){ return Long.parseLong(next()); }
double D() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | 2009e65176e990abbf52f5bffb3cf31d | train_003.jsonl | 1492965900 | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static boolean flag;
static char[][]maze;
static int n;
static int m;
static int ex;
static int ey;
static boolean[][]jl;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
while (sc.hasNext()) {
n=sc.nextInt();
m=sc.nextInt();
maze=new char[n][m];
jl=new boolean[n][m];
int dx=0;
int dy=0;
flag=false;
for(int i=0;i<n;i++){
String s=sc.next();
for(int j=0;j<m;j++){
maze[i][j]=s.charAt(j);
if(maze[i][j]=='S'){
dx=i;
dy=j;
}
else if(maze[i][j]=='T'){
ex=i;
ey=j;
}
}
}
dfs(dx,dy,-1,0);
if(flag)pw.println("YES");
else pw.println("NO");
pw.flush();
}
}
static void dfs(int i,int j,int pre,int turn){
if(i<0||i>=n||j<0||j>=m) return;
if(turn>=3)return;
if(turn==2){
if(pre==0){
if(i!=ex)return;
}
else if(pre==1){
if(j!=ey)return;
}else if(pre==2){
if(i!=ex)return;
}else if(pre==3){
if(j!=ey)return;
}
}
if(maze[i][j]=='*'||jl[i][j]) return;
if(maze[i][j]=='T'){
if(turn<=2){
flag=true;
}
return;
}
jl[i][j]=true;
if(pre==-1){
dfs(i,j-1,0,turn);
if(check(i,j-1))
jl[i][j-1]=false;
dfs(i-1,j,1,turn);
if(check(i-1,j))
jl[i-1][j]=false;
dfs(i,j+1,2,turn);
if(check(i,j+1))
jl[i][j+1]=false;
dfs(i+1,j,3,turn);
if(check(i+1,j))
jl[i+1][j]=false;
}
else if(pre==0){
dfs(i,j-1,0,turn);
if(check(i,j-1))
jl[i][j-1]=false;
dfs(i-1,j,1,turn+1);
if(check(i-1,j))
jl[i-1][j]=false;
dfs(i,j+1,2,turn+1);
if(check(i,j+1))
jl[i][j+1]=false;
dfs(i+1,j,3,turn+1);
if(check(i+1,j))
jl[i+1][j]=false;
}
else if(pre==1){
dfs(i,j-1,0,turn+1);
if(check(i,j-1))
jl[i][j-1]=false;
dfs(i-1,j,1,turn);
if(check(i-1,j))
jl[i-1][j]=false;
dfs(i,j+1,2,turn+1);
if(check(i,j+1))
jl[i][j+1]=false;
dfs(i+1,j,3,turn+1);
if(check(i+1,j))
jl[i+1][j]=false;
}
else if(pre==2){
dfs(i,j-1,0,turn+1);
if(check(i,j-1))
jl[i][j-1]=false;
dfs(i-1,j,1,turn+1);
if(check(i-1,j))
jl[i-1][j]=false;
dfs(i,j+1,2,turn);
if(check(i,j+1))
jl[i][j+1]=false;
dfs(i+1,j,3,turn+1);
if(check(i+1,j))
jl[i+1][j]=false;
}
else if(pre==3){
dfs(i,j-1,0,turn+1);
if(check(i,j-1))
jl[i][j-1]=false;
dfs(i-1,j,1,turn+1);
if(check(i-1,j))
jl[i-1][j]=false;
dfs(i,j+1,2,turn+1);
if(check(i,j+1))
jl[i][j+1]=false;
dfs(i+1,j,3,turn);
if(check(i+1,j))
jl[i+1][j]=false;
}
}
static boolean check(int i,int j){
if(i<0||i>=n||j<0||j>=m) return false;
return true;
}
}
| Java | ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."] | 3 seconds | ["YES", "NO"] | NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Java 8 | standard input | [
"graphs",
"implementation",
"dfs and similar",
"shortest paths"
] | 16a1c5dbe8549313bae6bca630047502 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." — an empty cell; "*" — a cell with road works; "S" — the cell where Igor's home is located; "T" — the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each. | 1,600 | In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise. | standard output | |
PASSED | b117ac8addd1ac6b7f47029d3f9777a5 | train_003.jsonl | 1385307000 | Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words, , where aj is the taste of the j-th chosen fruit and bj is its calories.Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem — now the happiness of a young couple is in your hands!Inna loves Dima very much so she wants to make the salad from at least one fruit. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.Stream;
public class Main implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final int MI = (int) 1e9;
static final long ML = (long) 1e18;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new Main(), "persefone", 1 << 32).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
int n = in.nextInt();
int k = in.nextInt();
int[] taste = new int[n + 1];
for (int i = 1; i <= n; i++) {
taste[i] = in.nextInt();
}
int[] caloris = new int[n + 1];
for (int i = 1; i <= n; i++) {
caloris[i] = in.nextInt() * k;
}
int[] dp = new int[110001];
Arrays.fill(dp, -MI);
dp[10000] = 0;
for (int i = 1; i <= n; i++) {
int diff = taste[i] - caloris[i];
if (diff >= 0) {
for (int j = 110000 - diff; j >= 0; j--) {
dp[j + diff] = Math.max(dp[j + diff], dp[j] + taste[i]);
}
} else {
for (int j = -diff; j <= 110000; j++) {
dp[j + diff] = Math.max(dp[j + diff], dp[j] + taste[i]);
}
}
}
printf(dp[10000] <= 0 ? -1 : dp[10000]);
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void flush() {
out.flush();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Reader(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
boolean isReady() throws IOException {
return br.ready();
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["3 2\n10 8 1\n2 7 1", "5 3\n4 4 4 4 4\n2 2 2 2 2"] | 1 second | ["18", "-1"] | NoteIn the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition fulfills, that's exactly what Inna wants.In the second test sample we cannot choose the fruits so as to follow Inna's principle. | Java 8 | standard input | [
"dp"
] | 91f0341e7f55bb03d87e4cfc63973295 | The first line of the input contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10). The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the fruits' tastes. The third line of the input contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100) — the fruits' calories. Fruit number i has taste ai and calories bi. | 1,900 | If there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer — the maximum possible sum of the taste values of the chosen fruits. | standard output | |
PASSED | 2bc3585ae05ad03255085e2400ff3045 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
// Scanner in = new Scanner(new File("input.txt"));
// PrintWriter out = new PrintWriter(new File("output.txt"));
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Map<String, Long> map = new HashMap<String, Long>();
int n = in.nextInt();
in.nextLine();
for (int i = 0; i < n; i++) {
String str = in.nextLine();
if (str.length() > 0) {
boolean next = true;
char x1 = str.charAt(0);
char x2 = '0';
for (int j = 1; j < str.length(); j++) {
char temp = str.charAt(j);
if (temp == x1) {
continue;
} else if (x2 == '0' || x2 == temp) {
x2 = temp;
} else {
next = false;
break;
}
}
if (next) {
if (x2 == '0') {
for (char ch = 'a'; ch <= 'z'; ch++) {
if (x1 != ch) {
String key = x1 > ch ? ch + "" + x1 : x1 + "" + ch;
long temp = 0;
if (map.containsKey(key)) {
temp = map.get(key);
}
map.put(key, str.length() + temp);
}
}
} else {
String key = x1 > x2 ? x2 + "" + x1 : x1 + "" + x2;
long temp = 0;
if (map.containsKey(key)) {
temp = map.get(key);
}
map.put(key, str.length() + temp);
}
}
}
}
if(map.isEmpty()){
out.print(0);
}else{
// ArrayList<String> mapKeys = new ArrayList(map.keySet());
// for (int i = 0; i < mapKeys.size(); i++) {
// out.print(mapKeys.get(i) + " ");
// }
// out.println();
//
ArrayList<Long> mapValues = new ArrayList(map.values());
// for (int i = 0; i < mapValues.size(); i++) {
// out.print(mapValues.get(i) + " ");
// }
// out.println();
Collections.sort(mapValues);
out.print(mapValues.get(mapValues.size() - 1));
}
out.close();
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | ba3188f2cc7faf653e2defd7dd4bbfdc | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.util.Scanner;
/**
* Created by Devan Kuleindiren on 05/11/15.
*/
public class A {
public static void main (String[] args) {
// Get input
Scanner scanner = new Scanner(System.in);
int noOfWords = scanner.nextInt();
// Process input
int[][] combinations = new int[26][26];
int max = Integer.MIN_VALUE;
for (int w = 0; w < noOfWords; w++) {
String temp = scanner.next();
char[] seenBefore = new char[2];
int[] numSeenBefore = new int[2];
int noDistinct = 0;
for (int i = 0; i < temp.length(); i++) {
char c = temp.charAt(i);
if (c == seenBefore[0]) {
numSeenBefore[0]++;
} else if (c == seenBefore[1]) {
numSeenBefore[1]++;
} else {
noDistinct++;
if (seenBefore[0] == 0) {
seenBefore[0] = c;
numSeenBefore[0] = 1;
} else {
seenBefore[1] = c;
numSeenBefore[1] = 1;
}
}
}
if (noDistinct == 1) {
int index = seenBefore[0] - 'a';
combinations[index][index] += numSeenBefore[0];
if (combinations[index][index] > max) max = combinations[index][index];
} else if (noDistinct == 2) {
int x = seenBefore[0] - 'a';
int y = seenBefore[1] - 'a';
if (y <= x) {
combinations[y][x] += numSeenBefore[0] + numSeenBefore[1];
if (combinations[y][x] > max) max = combinations[y][x];
} else {
combinations[x][y] += numSeenBefore[0] + numSeenBefore[1];
if (combinations[x][y] > max) max = combinations[x][y];
}
}
}
// Check all 2C words with 1C words
for (int row = 0; row < 26; row++) {
for (int col = row + 1; col < 25; col++) {
int tempNum = combinations[row][col] + combinations[row][row] + combinations[col][col];
if (tempNum > max) max = tempNum;
}
}
// Check biggest combination of just 1C words
int max1 = 0;
int max2 = 0;
for (int rowCol = 0; rowCol < 26; rowCol++) {
if (combinations[rowCol][rowCol] > max1) {
max2 = max1;
max1 = combinations[rowCol][rowCol];
} else if (combinations[rowCol][rowCol] > max2) {
max2 = combinations[rowCol][rowCol];
}
}
if (max1 + max2 > max) max = max1 + max2;
System.out.println(max);
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 0da7a56f93e55c00bd3c3bbf4b72e6c7 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mthai
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CF_593A solver = new CF_593A();
solver.solve(1, in, out);
out.close();
}
static class CF_593A {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
List<char[]> list = new ArrayList<>();
for (int i = 0; i < n; ++i) {
list.add(in.next().toCharArray());
}
int[] cnt1 = new int[26];
int[][] cnt2 = new int[26][26];
for (int i = 0; i < n; ++i) {
Set<Character> set = new TreeSet<>();
char[] a = list.get(i);
for (char c : a)
set.add(c);
Character[] set_c = new Character[set.size()];
set.toArray(set_c);
if (set_c.length == 1)
cnt1[set_c[0] - 'a'] += a.length;
if (set_c.length == 2)
cnt2[set_c[0] - 'a'][set_c[1] - 'a'] += a.length;
}
int ans = 0;
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < 26; ++j) {
if (i == j)
ans = Math.max(cnt1[j] + cnt2[i][j], ans);
else
ans = Math.max(cnt1[j] + cnt1[i] + cnt2[i][j] + cnt2[j][i], ans);
}
}
out.println(ans);
}
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 539c005434f8104b5c0345f6f3809407 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.util.*;
import java.io.*;
public class Attack {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader( System.in));
int n=Integer.parseInt(br.readLine());
int[] abc= new int[26];
String a,b;
char[] sorter;
HashMap<String,Integer>map=new HashMap<>();
StringBuilder sb;
Set<Character> charSet ;
char[] chars;
for(int i=0;i<n;i++){
a=br.readLine();
chars = a.toCharArray();
charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
b=sb.toString();
if(b.length()>2 /*|| b.length()==0*/)continue;
else if(b.length()==1)abc[b.charAt(0)-'a']+=a.length();
else if (b.length()==2){
sorter=b.toCharArray();
Arrays.sort(sorter);
b=String.valueOf(sorter);
if(map.containsKey(b)){
map.put(b, map.get(b)+a.length());
}
else map.put(b, a.length());
}
}
//System.out.println("TEST:"+('z'-'a'));
int max=0;
int max1=0;
int tempI=0;
int max2=0;
char temp1;
char temp2;
for(Map.Entry<String,Integer> e :map.entrySet()){
//System.out.println("key:"+e.getKey()+ " value:"+e.getValue());
temp1=e.getKey().charAt(0);
temp2=e.getKey().charAt(1);
max=Math.max(max,e.getValue()+abc[temp1-'a']+abc[temp2-'a']);
}
for(int i=0;i<26;i++){
if(max1<abc[i]){
max1=abc[i];
tempI=i;
}
}
for(int i=0;i<26;i++){
if(max2<abc[i] && i!=tempI){
max2=abc[i];
}
}
max=Math.max(max,max1+max2);
System.out.println(max);
br.close();
}//end of main function
}//end of Main class
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | aac583cbf33f3e0fb4807bfe781dfb5e | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
public class Solution {
class ListNode{
int val;
ListNode next;
int index ;
public ListNode(int i){
val = i;
}
}
class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
public String toString(){
return "s:"+start+" e:"+end;
}
};
public static void main(String [] args){
Solution sl = new Solution();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Map<String , Integer> mp = new HashMap<>();
Map<String , Integer> mpSingle = new HashMap<>();
int [] map = new int[26];
for (int i = 0 ; i < n ; i++) {
String s = in.next();
String key = "";
for (int k = 0 ; k < s.length() ; k++) {
map[s.charAt(k)-'a']++;
}
for (int k = 0 ; k < 26 ; k++){
if(map[k]>0){
key += ((char)(k+'a'));
}
}
if (key.length() == 2){
if (mp.containsKey(key)){
mp.put(key, mp.get(key)+s.length());
} else{
mp.put(key, s.length());
}
} else if (key.length() == 1){
if (mpSingle.containsKey(key)){
mpSingle.put(key, mpSingle.get(key) + s.length());
} else{
mpSingle.put(key, s.length());
}
}
map = new int[26];
key = "";
}
int mx1 = 0;
for (Entry e : mp.entrySet()){
String key = (String)e.getKey();
if (mpSingle.containsKey((key.substring(0,1)))){
mp.put(key, mp.get(key) + mpSingle.get((key.substring(0,1))));
}
if (mpSingle.containsKey(key.substring(1))){
mp.put(key, mp.get(key) + mpSingle.get(key.substring(1)));
}
}
for (Entry e : mp.entrySet()){
if ((Integer)e.getValue() > mx1){
mx1 = (Integer)e.getValue();
}
}
String ku = "";
int m3 = 0;
for (Entry e : mpSingle.entrySet()){
if ((Integer)e.getValue() > m3){
m3 = (Integer)e.getValue();
ku = (String)e.getKey();
}
}
mpSingle.remove(ku);
int mx2 = 0;
for (Entry e : mpSingle.entrySet()){
if ((Integer)e.getValue() > mx2){
mx2 = (Integer)e.getValue();
}
}
System.out.print(Math.max(mx1, mx2+m3));
}
public void printList(int [] a){
for (int i = 0 ; i < a.length ; i++){
System.out.print(a[i]+"");
}
}
public void printList(String [] a){
for (int i = 0 ; i < a.length ; i++){
System.out.print(a[i]+"");
}
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 09c312f327a59d238d3c11e088350b97 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 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 Main {
static int MOD = 1000 * 1000 * 1000 + 7;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
System.exit(0);
}
private static void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
char[][] s = new char[n][];
for (int i = 0; i < n; i++) {
s[i] = in.next().toCharArray();
}
int res = 0;
for (int i = 0; i < 26; i++) {
for (int j = i + 1; j < 26; j++) {
int total = 0;
for (int k = 0; k < n; k++) {
int c = 0;
for (int l = 0; l < s[k].length; l++) {
if (s[k][l] == 'a' + i || s[k][l] == 'a' + j) {
c++;
}
}
total += (c == s[k].length ? c : 0);
}
res = Math.max(res, total);
}
}
out.print(res);
}
/*
*
*/
// --------------------------------------------------------
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());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 68f4ccb0f34097e693e0dade72f2e753 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 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 Main {
static int MOD = 1000 * 1000 * 1000 + 7;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
System.exit(0);
}
private static void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
char[][] s = new char[n][];
for (int i = 0; i < n; i++) {
s[i] = in.next().toCharArray();
}
int best = Integer.MIN_VALUE;
for (char ch1 = 'a'; ch1 <= 'z'; ch1++) {
for (char ch2 = (char) (ch1 + 1); ch2 <= 'z'; ch2++) {
int count = 0;
for (int i = 0; i < n; i++) {
boolean isOk = true;
for (int j = 0; j < s[i].length; j++) {
if (s[i][j] != ch1 && s[i][j] != ch2) {
isOk = false;
}
}
if (isOk) {
count += s[i].length;
}
}
best = Math.max(best, count);
}
}
out.print(best);
}
/*
*
*/
// --------------------------------------------------------
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());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | c018795717ffb5764d2221e30d2ea510 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 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 Main {
static int MOD = 1000 * 1000 * 1000 + 7;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
System.exit(0);
}
private static void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
char[][] s = new char[n][];
for (int i = 0; i < n; i++) {
s[i] = in.next().toCharArray();
}
int[] count1 = new int[26];
int[][] count2 = new int[26][26];
int res = 0;
for (int i = 0; i < n; i++) {
char first = 0;
char second = 0;
char third = 0;
for (int j = 0; j < s[i].length; j++) {
if (first == 0 || s[i][j] == first) {
first = s[i][j];
continue;
}
if (second == 0 || s[i][j] == second) {
second = s[i][j];
continue;
}
if (third == 0 || s[i][j] == third) {
third = s[i][j];
continue;
}
}
if (third != 0) {
continue;
}
if (second != 0) {
count2[first - 'a'][second - 'a'] += s[i].length;
count2[second - 'a'][first - 'a'] += s[i].length;
continue;
}
if (first != 0) {
count1[first - 'a'] += s[i].length;
}
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
if (i == j) {
continue;
}
res = Math.max(res, count1[i] + count1[j] + count2[i][j]);
}
}
out.print(res);
}
/*
*
*/
// --------------------------------------------------------
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());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 464f91508c9fdb0442fb85cb6bf5c7e0 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class TwoChar {
public static BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
public static StringTokenizer st;
public static void main(String[] args) throws IOException {
int n = nextInt();
int[] a = new int[n];
List<List<Integer>> chars = new ArrayList<List<Integer>>();
for (int i = 0; i < n; i++) {
String s = nextString();
List<Integer> list = new ArrayList<Integer>();
for (int j = 0; j < 26; j++)
if (s.indexOf((char)('a' + j)) >= 0)
list.add(j);
chars.add(list);
a[i] = list.size() <= 2 ? s.length() : 0;
}
int max = 0;
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++) {
int sum = 0;
for (int k = 0; k < n; k++)
if (a[k] > 0) {
boolean b = true;
for (int x : chars.get(k))
if (x != i && x != j)
b = false;
if (b)
sum += a[k];
}
max = Math.max(max, sum);
}
System.out.println(max);
}
public static String nextLine() throws IOException {
return f.readLine();
}
public static String nextString() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(f.readLine());
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public static int[] intArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public static long[] longArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | a61708c508905becb07b8e949f0df73c | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int w=sc.nextInt();
int[] countCh= new int[26];
int[][] countChp= new int[26][26];
ArrayList<String> str= new ArrayList<String>();
for(int i=0;i<w;i++)
{
//
String t=sc.next();
char[] arr= t.toCharArray();
Arrays.sort(arr);
int count=0;
char check=arr[0];
for(char c:arr)
{
if(c!=check){
count++;
check=c;
}
if(count==2)break;
}
if(count<2)
{
str.add(t);
if(count==0)
{
countCh[arr[0]-'a']+=t.length();
}
if(count==1)
{
countChp[arr[0]-'a'][check-'a']+=t.length();
}
}
}
int max=0,idx1=-1,idx2=-1;
for(int i=0;i<26;i++)
{
for(int j=0;j<26;j++)
{
if(i==j)continue;
if(countCh[i]+countCh[j]+countChp[i][j] > max)
{
max=countCh[i]+countCh[j]+countChp[i][j];
idx1=i;idx2=j;
}
}
}
int ans=0;
for(int i=0;i<str.size();i++)
{
ans+=str.get(i).length();
char[] arr= str.get(i).toCharArray();
for(char c:arr)
{
if(c-'a' -idx1 !=0 && c-'a' - idx2 !=0)
{
ans-=str.get(i).length();
break;
}
}
}
System.out.print(ans);
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | dbb9c29bf2e6245d5ca9b36398dde437 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int w=sc.nextInt();
int[] countCh= new int[26];
int[][] countChp= new int[26][26];
ArrayList<String> str= new ArrayList<String>();
for(int i=0;i<w;i++)
{
//
String t=sc.next();
char[] arr= t.toCharArray();
Arrays.sort(arr);
int count=0;
char check=arr[0];
for(char c:arr)
{
if(c!=check){
count++;
check=c;
}
if(count==2)break;
}
if(count<2)
{
str.add(t);
if(count==0)
{
countCh[arr[0]-'a']+=t.length();
}
if(count==1)
{
countChp[arr[0]-'a'][check-'a']+=t.length();
}
}
}
int max=0;
for(int i=0;i<26;i++)
{
for(int j=0;j<26;j++)
{
if(i==j)continue;
if(countCh[i]+countCh[j]+countChp[i][j] > max)
max=countCh[i]+countCh[j]+countChp[i][j];
}
}
System.out.print(max);
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | db8045bb10c234b29e12661489294412 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[][] dp = new int[26][26];
String[] v = new String[n];
for (int i = 0; i < n; ++i) v[i] = in.next();
for (int i = 0; i < 26; ++i) {
for (int j = i; j < 26; ++j) {
for (int k = 0; k < n; ++k) {
char[] a = v[k].toCharArray();
int sum = 0;
for (int x = 0; x < a.length; ++x) {
if (a[x] != i + 'a' && a[x] != j + 'a') {
sum = 0;
break;
}
++sum;
}
dp[i][j] += sum;
}
}
}
int res = 0;
for (int i = 0; i < 26; ++i) {
for (int j = i; j < 26; ++j) {
res = Math.max(res, dp[i][j]);
}
}
out.println(res);
}
}
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\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | c11e00ac6710de9eba9ebdfd4be21d29 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String arr[] = new String[n];
for (int i = 0; i < n; ++i) {
arr[i] = in.next();
}
int max = -1;
for (int i = 0; i < 26; ++i) {
for (int j = i; j < 26; ++j) {
char first = (char) ('a' + i);
char second = (char) ('a' + j);
int sum = 0;
for (int k = 0; k < n; ++k) {
int cnt = 0;
for (int l = 0; l < arr[k].length(); ++l) {
if (arr[k].charAt(l) != first && arr[k].charAt(l) != second) {
cnt = 0;
break;
}
cnt++;
}
sum += cnt;
}
max = Math.max(sum, max);
}
}
out.println(max);
}
}
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\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 7a56cf30a66858e4571b0ca0dca9b57d | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.util.Scanner;
public class TwoChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] words = new String[n];
for (int i = 0; i < n; i++) {
words[i] = sc.nextLine();
}
System.out.println(maximizeArticle(words));
sc.close();
}
static int maximizeArticle(String[] words) {
int n = words.length;
int result = 0;
for (char c = 'a'; c <= 'y'; c++) {
for (char d = (char) (c + 1); d <= 'z'; d++) {
int temp = 0;
for (int i = 0; i < n; i++) {
temp += score(words[i], c, d);
}
if (temp > result) result = temp;
}
}
return result;
}
static int score(String word, char a, char b) {
char[] letters = word.toCharArray();
for (char c : letters) {
if (c != a && c != b) {
return 0;
}
}
return letters.length;
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | b3d8f817e52a6763d697f8f19fa161e2 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.util.*;
import java.io.*;
/**
*
* @author Prateek Goel
*/
public class A2Char {
public static void main(String args[])throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String arr[]=new String[n];
HashSet<Character> hsChar = new HashSet<Character>();
for(int r=0;r<n;r++){
arr[r] = br.readLine();
HashSet<Character> hs = new HashSet<Character>();
for(int i=0;i<arr[r].length();i++){
hs.add(arr[r].charAt(i));
hsChar.add(arr[r].charAt(i));
}
if(hs.size()>2){
arr[r]="`";
}
}
ArrayList<Character> al=new ArrayList<Character>(hsChar);
if(al.size()!=1){
int max =Integer.MIN_VALUE;
for(int i=0;i<al.size()-1;i++){
char a=al.get(i);
for(int j=i+1;j<al.size();j++){
char b=al.get(j);
int len=0;
for(int k=0;k<arr.length;k++){
int flag=0;
for(int y=0;y<arr[k].length();y++){
if(arr[k].charAt(y)==a ||arr[k].charAt(y)==b){}
else
{
flag=1;
break;
}
}
if(flag==0){
len +=arr[k].length();
}
}
if(len > max){
max =len;
}
}
}
System.out.println(max);
}
else{
int len=0;
for(int k=0;k<arr.length;k++){
len +=arr[k].length();
}
System.out.println(len);
}
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 8467b00592ded929fcf2cd9315dd36cf | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | //package R329;
import java.io.*;
import java.util.*;
public class R329 {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String linea;
int n = Integer.parseInt(in.readLine());
Set<String> tsArticle, tsletters;
tsletters = new TreeSet();
String cad;
int arrLens[] = new int[n];
String arrArts[] = new String[n];
for (int i = 0; i < n; i++) {
linea = in.readLine();
tsArticle = new TreeSet(Arrays.asList(linea.split("")));
tsletters.addAll(Arrays.asList(linea.split("")));
cad = "";
arrLens[i] = linea.length();
for(String letter : tsArticle)
cad += letter;
arrArts[i] = cad;
}
String arrLetters[] = new String[tsletters.size()];
int ind = 0;
for (String letter : tsletters){
arrLetters[ind] = letter;
ind += 1;
}
List<Integer> longitudes = new ArrayList();
int longitud;
for (int i = 0; i < arrLetters.length; i++) {
for (int j = 0; j < arrLetters.length; j++) {
longitud = 0;
for (int k = 0; k < n; k++) {
if (arrLetters[i].compareTo(arrArts[k]) == 0 || arrLetters[j].compareTo(arrArts[k]) == 0 || arrLetters[i].concat(arrLetters[j]).compareTo(arrArts[k]) == 0 ) {
longitud += arrLens[k];
}
}
longitudes.add(longitud);
}
}
System.out.println(Collections.max(longitudes));
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | c0e12247b5efabec6c6601c39a9537c1 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Created by WiNDWAY on 5/3/16.
*/
public class Codeforces_round_329_div_2_2Char {
public static void main(String[] args) {
FScanner input = new FScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
int size = input.nextInt();
Map<String, Integer> data = new TreeMap<String, Integer>();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < size; ++i){
char[] s = input.next().toCharArray();
String result = "";
for (int j = 0; j < s.length; ++j){
if (!result.contains(Character.toString(s[j]))) result += s[j];
}
if (result.length() < 3) {
if (data.containsKey(result)) data.put(result, data.get(result) + s.length);
else data.put(result, s.length);
}
}
int max = 0;
for (int i = 0; i < 26; ++i){
for (int j = i; j < 26; ++j){
int temp = 0;
for (String s : data.keySet()){
if (s.equals(String.valueOf(alphabet.charAt(i)) + String.valueOf(alphabet.charAt(j))) ||
s.equals(String.valueOf(alphabet.charAt(j)) + String.valueOf(alphabet.charAt(i))) ||
s.equals(String.valueOf(alphabet.charAt(i))) ||
s.equals(String.valueOf(alphabet.charAt(j)))){
temp += data.get(s);
}
}
max = Math.max(temp, max);
}
}
out.println(max);
out.close();
}
public static PrintWriter out;
public static class Article {
HashMap<Character, Integer> map;
public Article(String current) {
map = new HashMap<>();
for (int j = 0; j < current.length(); j++) {
if (!map.containsKey(current.charAt(j))) {
map.put(current.charAt(j), 1);
} else {
map.put(current.charAt(j), map.get(current.charAt(j)) + 1);
}
}
}
}
public static class FScanner {
BufferedReader br;
StringTokenizer st;
public FScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private 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());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 3829e41d637d8b245ab841307f8789a8 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.util.*;
public class BruteForce {
public static Scanner in =new Scanner(System.in);
public static boolean check(String txt){
HashSet<Integer> set=new HashSet<Integer>();
for(int i=0;i<txt.length();i++)
set.add((int)txt.charAt(i));
if(set.size()>2)
return false;
else
return true;
}
public static long getCost(ArrayList<String>list,char a,char b){
long cost=0;
if(a==b){
for(int i=0;i<list.size();i++){
int count=0;
String cur=list.get(i);
for(int j=0;j<cur.length();j++){
if(cur.charAt(j)==a)
count++;
else{
count=0;
break;
}
}
cost+=count;
}
}
else{
for(int i=0;i<list.size();i++){
int count=0;
String cur=list.get(i);
for(int j=0;j<cur.length();j++){
if(cur.charAt(j)==a||cur.charAt(j)==b)
count++;
else{
count=0;
break;
}
}
cost+=count;
}
}
return cost;
}
public static void main(String[] args) {
int n=in.nextInt();
ArrayList<String>list=new ArrayList<String>();
for(int i=0;i<n;i++){
String cur=in.next();
if(check(cur))
list.add(cur);
}
long max=0;
for(char i='a';i<='z';i++){
for(char j='a';j<='z';j++){
long cur=getCost(list,i,j);
max=Math.max(cur,max);
}
}
System.out.println(max);
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 1ad23144b30cc2cd8f94a2f1b946314a | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | //package CodeForces.Round329;
import java.util.*;
/**
* Created by ilya on 04.11.15.
*/
public class A2Char {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
TreeMap<Character, Integer> map = new TreeMap<>();
TreeMap<String, Integer> map2 = new TreeMap<>();
String a;
Integer max = 0;
Character b = null, c = null;
String tmp = null;
outer:
for (int i = 0; i < n; i++) {
a = sc.next();
b = a.charAt(0);
c = null;
for (int j = 1; j < a.length(); j++) {
if(c == null && a.charAt(j) != b ) c = a.charAt(j);
if(c != null && a.charAt(j) != b && a.charAt(j)!= c) continue outer;
}
if(c != null) tmp = b<c? String.valueOf(b)+String.valueOf(c) : String.valueOf(c)+String.valueOf(b);
if (c == null && map.containsKey(b))
map.put(b, map.get(b) + a.length());
else if (c == null && !map.containsKey(b))
map.put(b, a.length());
else if (map2.containsKey(tmp))
map2.put(tmp, map2.get(tmp) + a.length());
else if (!map2.containsKey(tmp))
map2.put(tmp, a.length());
}
for (Map.Entry<String, Integer> se : map2.entrySet()) {
if(map.containsKey(se.getKey().charAt(0))) se.setValue(se.getValue() + map.get(se.getKey().charAt(0)));
if(map.containsKey(se.getKey().charAt(1))) se.setValue(se.getValue() + map.get(se.getKey().charAt(1)));
}
List<Integer> list1 = new ArrayList<>(map.values());
List<Integer> list2 = new ArrayList<>(map2.values());
Collections.sort(list1, Comparator.<Integer>reverseOrder());
Collections.sort(list2, Comparator.<Integer>reverseOrder());
if (list1.size() > 1 && max < list1.get(0) + list1.get(1)) max = list1.get(0) + list1.get(1);
if (list1.size() > 0 && max < list1.get(0)) max = list1.get(0);
if (list2.size() > 0 && max < list2.get(0)) max = list2.get(0);
System.out.println(max);
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 3aee46539dda3b8047c2f8c8c7605cc9 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Two2Char
{
static String[] inp;
static int[][] freq;
static boolean isInvalid(int[] x,int[] y){
int ct = 0;
for(int i = 0; i < 26; ++i){
if(x[i] > 0 || y[i] > 0)
ct++;
}
if(ct > 2)
return true;
return false;
}
static int getFreqVal(int[] x){
int sum = 0;
for(int i = 0; i < 26; ++i)
sum += x[i];
return sum;
}
static int[] getCombinedFreq(int[] x,int[] y){
int[] z = new int[26];
for(int i = 0; i < 26;++i)
z[i] = x[i] + y[i];
return z;
}
static void calcFreq(int i,String x){
for(char temp:x.toCharArray()){
freq[i][temp - 'a']++;
}
}
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int wc = Integer.parseInt(br.readLine());
inp = new String[wc];
freq = new int[wc][26];
StringBuilder sb = new StringBuilder();
for(int i = 0; i < wc;++i){
inp[i] = br.readLine();
calcFreq(i,inp[i]);
}
int max = 0;
for(int i = 0; i < wc;++i){
if(isInvalid(freq[i],freq[i]))
continue;
for(int j = 0; j < wc; ++j){
int temp = getFreqVal(freq[i]);
if(i == j){
if(max < temp)
max = temp;
continue;
}
if(isInvalid(freq[i],freq[j])){
if(max < temp)
max = temp;
continue;
}
temp += getFreqVal(freq[j]);
int[] temparr = getCombinedFreq(freq[i],freq[j]);
for(int k = 0; k < wc;++k){
if(k == i || k == j){
if(max < temp)
max = temp;
continue;
}
if(isInvalid(freq[k],temparr)){
if(max < temp)
max = temp;
continue;
}
temparr = getCombinedFreq(temparr,freq[k]);
temp += getFreqVal(freq[k]);
}
if(max < temp)
max = temp;
}
}
System.out.println(max);
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 2790b5a6f503c5164e329953c2b62dbc | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | //package codeforces;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class A implements Closeable {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
A() throws IOException {
// reader = new BufferedReader(new FileReader("input.txt"));
// writer = new PrintWriter(new FileWriter("output.txt"));
}
StringTokenizer stringTokenizer;
String next() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.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());
}
private int MOD = 1000 * 1000 * 1000 + 7;
int sum(int a, int b) {
a += b;
return a >= MOD ? a - MOD : a;
}
int product(int a, int b) {
return (int) (1l * a * b % MOD);
}
int pow(int x, int k) {
int result = 1;
while (k > 0) {
if (k % 2 == 1) {
result = product(result, x);
}
x = product(x, x);
k /= 2;
}
return result;
}
int inv(int x) {
return pow(x, MOD - 2);
}
void solve() throws IOException {
int n = nextInt();
int[] masks = new int[n];
String[] strings = new String[n];
for(int i = 0; i < n; i++) {
strings[i] = next();
for (char c : strings[i].toCharArray()) {
masks[i] |= 1 << c - 'a';
}
}
int answer = 0;
for(int i = 0; i < 26; i++) {
for(int j = i + 1; j < 26; j++) {
int mask = (1 << i) + (1 << j);
int totalLength = 0;
for(int k = 0; k < n; k++) {
if((mask | masks[k]) == mask) {
totalLength += strings[k].length();
}
}
answer = Math.max(answer, totalLength);
}
}
writer.println(answer);
}
public static void main(String[] args) throws IOException {
try (A a = new A()) {
a.solve();
}
}
@Override
public void close() throws IOException {
reader.close();
writer.close();
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 20491a571435410428477b4ce2e9cc2d | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main593A2
{
static PrintWriter out=new PrintWriter(System.out);
static Vector<Character> contains(String s)
{
Vector<Character> letters=new Vector<Character>();
for(int i=0;i<s.length();i++)
{
if(!letters.contains(s.charAt(i)))
letters.add(s.charAt(i));
}
return letters;
}
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] cnt1=new int[26];
int[][] cnt2=new int[26][26];
while(n-->0)
{
String s=sc.next();
Vector<Character> dis=new Vector<Character>();
dis=contains(s);
if(dis.size()==1)
cnt1[(int)dis.elementAt(0)-97]+=s.length();
else if(dis.size()==2)
{
cnt2[(int)dis.elementAt(1)-97][(int)dis.elementAt(0)-97]+=s.length();
cnt2[(int)dis.elementAt(0)-97][(int)dis.elementAt(1)-97]+=s.length();
}
}
int max=0;
for(int i=0;i<26;i++)
{
for(int j=0;j<26;j++)
{
if(i==j) continue;
int value=cnt1[i]+cnt1[j]+cnt2[i][j];
if(value>max)
max=value;
}
}
out.println(max);
out.flush();
}
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 0412ef5dec7f1bb964a512676b9d560a | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class a {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int N = scan.nextInt();
ArrayList<String> list = new ArrayList<String>();
for (int i =0;i<N;i++)list.add(scan.next());
HashMap<String, Integer> map = new HashMap<>();
int max = 0;
for (String s : list) {
char[] temp = s.toCharArray();
char a='.',b='.', t='.';
boolean possible = true;
for (char c : temp){
if (a=='.') a=c;
else if (c==a)continue;
else if (b=='.')b=c;
else if (c!=a && c!=b){possible=false;break;}
}
if(!possible)continue;
if (b=='.'){
for (char i = 'a';i<='z';i=(char)(i+1)){
if(a==i)continue;
String m = (a<i)?a+""+i:i+""+a;
if (map.containsKey(m))map.put(m, map.get(m)+s.length());
else map.put(m, s.length());
if (map.get(m)>max)max=map.get(m);
}
continue;
}
if (a>b){t=a;a=b;b=t;}
String m = a+""+b;
if (map.containsKey(m))map.put(m, map.get(m)+s.length());
else map.put(m, s.length());
if (map.get(m)>max)max=map.get(m);
}
System.out.println(max);
}
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 12d687f095a8ac113a3dce3c81edae82 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Reza_mh
*/
public class A {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
int n = Integer.parseInt(br.readLine());
ArrayList<String> alist = new ArrayList<String>();
ArrayList<String> slist = new ArrayList<String>();
long max = 0;
for (int i = 0; i < n; i++) {
String str = br.readLine();
TreeSet<Character> ts = new TreeSet<Character>();
for (int j = 0; j < str.length(); j++) {
ts.add(str.charAt(j));
}
if (ts.size() == 2) {
Iterator<Character> it = ts.iterator();
Character a = it.next();
Character b = it.next();
String string = a + "" + b;
if (tm.containsKey(string)) {
int number = tm.get(string);
tm.remove(string);
tm.put(string, number + str.length());
} else {
alist.add(string);
tm.put(string, str.length());
}
} else if (ts.size() == 1) {
Iterator<Character> it = ts.iterator();
Character a = it.next();
String string = a + "";
if (tm.containsKey(string)) {
int number = tm.get(string);
tm.remove(string);
tm.put(string, number + str.length());
} else {
alist.add(string);
slist.add(string);
tm.put(string, str.length());
}
}
}
for (int i = 0; i < alist.size(); i++) {
String st = alist.get(i);
if (st.length() == 2) {
int number = tm.get(st);
if (tm.containsKey(st.charAt(0) + "")) {
number += tm.get(st.charAt(0) + "");
}
if (tm.containsKey(st.charAt(1) + "")) {
number += tm.get(st.charAt(1) + "");
}
if (max < number) {
max = number;
}
}
}
int size[]=new int[slist.size()];
for (int i = 0; i < slist.size(); i++) {
size[i]=tm.get(slist.get(i));
}
Arrays.sort(size);
if(slist.size()>=2){
if(max<size[slist.size()-1]+size[slist.size()-2]){
max=size[slist.size()-1]+size[slist.size()-2];
}
}else if(slist.size()==1){
max=Math.max(max, size[0]);
}
System.out.println(max);
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | dbff61c9a6acf429889bf42e549f39cf | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | //package round_329;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String []s = new String[n+1];
for (int i = 1; i <= n; i++) {
s[i] = sc.next();
}
int max = -1;
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
int cnt = 0;
for (int k = 1; k <= n; k++) {
boolean ok = true;
for (int l = 0; l < s[k].length(); l++) {
int x =s[k].charAt(l)-'a';
if(x!=i && x!=j){
ok = false;
break;
}
}
if(ok){
cnt+=s[k].length();
}
}
max = Math.max(cnt, max);
}
}
System.out.println(max);
sc.close();
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 1d77244413dce258f3d4da08dd6ef1ea | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/**
*
* @author Zhasan
*/
//---------------------------------------- BETTER THAN THE ORIGINAL SOLUTION DEEEE---------------------------------------------------
public class A593 {
public static void main(String argsg[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String toId = "";
String[] w = new String[n];
for (int i = 0; i < n; i++) {
w[i] = in.next();
toId += w[i];
}
String letters = id(toId);
// System.out.println(letters);
int max = Integer.MIN_VALUE;
Map<Character, Integer> num = new HashMap<>();
for (int i = 0; i < letters.length(); i++) {
int c = 0;
for (int j = 0; j < w.length; j++) {
String id = id(w[j]);
if (id.length() == 1 && letters.charAt(i) == id.charAt(0)) {
c+=w[j].length();
}
}
num.put(letters.charAt(i), c);
}
max = num.get(letters.charAt(0));
for (int i = 0; i < letters.length(); i++) {
for (int j = 0; j < letters.length(); j++) {
if (i != j) {
int count = 0;
for (int jj = 0; jj < w.length; jj++) {
String id = id(w[jj]);
if (id.length() < 3) {
if (id.contains(letters.charAt(i) + "") && id.contains(letters.charAt(j) + "")) {
count+=w[jj].length();
}
}
}
int tCount = count + num.get(letters.charAt(i)) + num.get(letters.charAt(j));
// System.out.println(tCount);
if (tCount > max) {
max = tCount;
}
}
}
}
System.out.println(max);
}
public static String id(String str) {
Set<Character> toSort = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
toSort.add(c);
}
Iterator i = toSort.iterator();
char ch[] = new char[toSort.size()];
int j = 0;
while (i.hasNext()) {
ch[j] = (char) i.next();
j++;
}
Arrays.sort(ch);
String res = "";
for (Character ch1 : ch) {
res = res + ch1;
}
return res;
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | ccd5b233a0e9f8bd4aed3ab340e391e1 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void main( String[] args )
{
Scan scan = new Scan();
int n = scan.nextInt();
int[] sum=new int[26];
Arrays.fill(sum, 0);
int[][] sum2=new int[26][];
for(int i=0; i<26; i++)
{
sum2[i]=new int[26];
Arrays.fill(sum2[i], 0);
}
for(int i=0; i<n; i++)
{
String s=scan.next();
int[] cnt=new int[26];
Arrays.fill(cnt, 0);
int l=s.length();
for(int j=0; j<l; j++)
cnt[s.charAt(j)-'a']++;
int a=-1, b=-1;
boolean valid=true;
for(int j=0; j<26; j++)
{
if(cnt[j]==0)
continue;
if(a==-1)
a=j;
else if(b==-1)
b=j;
else
valid=false;
}
if(!valid)
continue;
if(b==-1)
sum[a]+=cnt[a];
else
sum2[a][b]+=cnt[a]+cnt[b];
}
int ans=0;
for(int i=0; i<26; i++)
for(int j=i+1; j<26; j++)
ans=Math.max(ans, sum[i]+sum[j]+sum2[i][j]);
System.out.println( ans );
}
}
class Scan
{
BufferedReader br;
StringTokenizer st;
Scan()
{
br = new BufferedReader( new InputStreamReader( System.in ) );
}
boolean hasNext()
{
while ( st == null || ! st.hasMoreElements() )
{
try
{
st = new StringTokenizer( br.readLine() );
}
catch ( Exception e )
{
return false;
}
}
return true;
}
String next()
{
if ( hasNext() )
return st.nextToken();
return null;
}
int nextInt()
{
if ( hasNext() )
return Integer.parseInt( st.nextToken() );
return -1;
}
String nextLine()
{
st = null;
try
{
return br.readLine();
}
catch ( Exception e )
{
return null;
}
}
double nextDouble()
{
if ( hasNext() )
return Double.parseDouble( st.nextToken() );
return -1;
}
BigInteger nextBigInteger()
{
if ( hasNext() )
return new BigInteger( st.nextToken() );
return null;
}
long nextLong()
{
if ( hasNext() )
return Long.parseLong( st.nextToken() );
return -1;
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 95a73d8277c2094a37ccf3e729336fa0 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.*;
import java.util.*;
public class SolveA {
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static void main(String[] args) throws IOException {
new SolveA().run();
}
public void solve() throws IOException {
int n = nextInt();
String[] words = new String[n];
for (int i = 0; i < n; i++) {
words[i] = nextToken();
}
int answer = 0;
for (int i = 0; i < 25; i++) {
for (int j = i + 1; j < 26; j++) {
int counter = 0;
for (int k = 0; k < n; k++) {
if (cont(words[k], i, j)) {
counter += words[k].length();
}
}
answer = Math.max(answer, counter);
}
}
out.println(answer);
}
boolean cont(String s, int a, int b) {
boolean ans = true;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c - 'a' != a && c - 'a' != b) {
ans = false;
break;
}
}
return ans;
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in)); // new
// InputStreamReader(System.in)
out = new PrintWriter(System.out); // System.out
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | fc89e10ff07dd5ea92625f89c982341f | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.util.Scanner;
/**
* Created by saturn on 20.05.2017.
*/
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String dane[] = new String[n];
for (int i = 0; i < n; ++i) {
dane[i] = in.next();
}
int max = -1;
for (int i = 0; i < 26; ++i) {
for (int j = i; j < 26; ++j) {
char a = (char) ('a' + i);
char b = (char) ('a' + j);
int suma = 0;
for (int k = 0; k < n; ++k) {
int chk = 0;
for (int l = 0; l < dane[k].length(); ++l) {
if (dane[k].charAt(l) != a && dane[k].charAt(l) != b) {
chk = 0;
break;
}
chk++;
}
suma += chk;
}
max = Math.max(suma, max);
}
}
System.out.println(max);
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 9fb0607504b6ea2ceff2535ebbf7593d | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | //package prepare2VKOSHP;
import java.io.IOException;
import java.util.Scanner;
public class A {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String arr[] = new String[n];
int num=0;
for(int i = 0; i<n; i++){
int tmp = 0;
String temp = sc.next();
for(int k = 0; k<26; k++){
if(temp.indexOf(k+'a')!=-1){tmp++;if(tmp>2)break;}
}
if(tmp<=2){arr[num]=temp;num++;}
}
int max=0;//char one = 0, two = 0;
for(int i = 0; i<26; i++){
for(int k = 0; k<26; k++){
if(i==k) continue;
int now = 0;
char lol1 = (char)(i+'a');
char lol2 = (char)(k+'a');
for(int j=0; j<num; j++){
int tmptmp = counter(arr[j],lol1)+counter(arr[j],lol2);
if(tmptmp==arr[j].length())
now+=tmptmp;
}
if(max<now){
max=now;
//one = lol1;
//two = lol2;
}
}
}
/* int res=0;
for(int i = 0; i<num; i++){
if(counter(arr[i],one)+counter(arr[i],two)==arr[i].length())
res+=arr[i].length();
}*/
System.out.println(max);
System.exit(0);
}
static int counter(String s, char c){
int res = 0;
for(int i = 0; i<s.length(); i++)
res = s.charAt(i)==c?res+1:res;
return res;
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 70c05aae8e290c2f976b9296f108a288 | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class A
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
String FInput="";
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ,\t");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
catch (NullPointerException e)
{
line=null;
}
}
long NextLong()
{
String n = inputParser.nextToken();
long val = Long.parseLong(n);
return val;
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
double NextDouble()
{
String n = inputParser.nextToken();
double val = Double.parseDouble(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
//String filePath="circles.in";
String filePath=null;
if(argv.length>0)filePath=argv[0];
new A(filePath);
}
public A(String inputFile)
{
openInput(inputFile);
//readNextLine();
int T=1;//NextInt();
StringBuilder sb = new StringBuilder();
for(int t=1; t<=T; t++)
{
readNextLine();
int N=NextInt();
String [] a = new String[N];
for(int i=0; i<N; i++)
{
readNextLine();
a[i] = NextString();
}
int ret=0;
for(char x='a'; x<='z'; x++)
for(char y='a'; y<='z'; y++)
{
int now=0;
for(int i=0; i<N; i++)
{
boolean ok=true;
for(int j=0; j<a[i].length(); j++)
if(a[i].charAt(j)!=x&&a[i].charAt(j)!=y)ok=false;
if(ok)now+=a[i].length();
}
ret = Math.max(ret, now);
}
sb.append(ret);
}
System.out.print(sb);
closeInput();
}
} | Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | 02a2e4bca55c0dcb1e47fc7b6316028a | train_003.jsonl | 1446655500 | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. | 256 megabytes | import java.util.*;
public class P2Char {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
int[] oneTimes = new int[26];
int[][][] twoTimes = new int[26][26][2];
int count2 = 0;
for(int i = 0; i < n; i++){
int[] ls = new int[26];
char[] word = inp.next().toCharArray();
for(char c : word)
ls[c-'a']++;
int count = -1;
int[] res = new int[2];
for(char nc = 0; nc < ls.length; nc++){
if(ls[nc] > 0){
count++;
if(count > 1)
break;
res[count] = (nc);
}
}
if(count == 0)
oneTimes[res[0]] += ls[res[0]];
if(count == 1){
twoTimes[res[0]][res[1]][0] += ls[res[0]];
twoTimes[res[0]][res[1]][1] += ls[res[1]];
}
}
int max = 0, temp;
for(int i = 0; i < oneTimes.length; i++){
if(oneTimes[i] > max)
max = oneTimes[i];
}
for(int i = 0; i < 26; i++){
for(int j = i+1; j < 26; j++){
temp = oneTimes[i] + twoTimes[i][j][0] + oneTimes[j] + twoTimes[i][j][1];
if(max < temp)
max = temp;
}
}
System.out.println(max);
}
}
| Java | ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"] | 2 seconds | ["9", "6"] | NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. | Java 8 | standard input | [
"implementation",
"brute force"
] | d8a93129cb5e7f05a5d6bbeedbd9ef1a | The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. | 1,200 | Print a single integer — the maximum possible total length of words in Andrew's article. | standard output | |
PASSED | a3f2d28970809f7f804f29922e66f450 | train_003.jsonl | 1579703700 | There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j < t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way. | 256 megabytes |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t>0){
int n =scanner.nextInt()+1;
int arr[][] = new int[n][2];
arr[0][0] = 0;
arr[0][1] = 0;
for(int i=1;i<n;i++){
arr[i][0] = scanner.nextInt();
arr[i][1] = scanner.nextInt();
}
Arrays.sort(arr, Comparator.comparingInt(a -> a[0]));
Arrays.sort(arr, Comparator.comparingInt(b -> b[1]));
boolean flag = true;
for (int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr[i][0]-arr[j][0]>0){
flag =false;
//System.out.println("This "+arr[i][1]+ "ne this"+j);
}
}
}
List<Character> characters = new ArrayList<>();
for(int i=0;i<n-1;i++){
if(arr[i][0]-arr[i+1][0]<0){
int buff = arr[i+1][0]-arr[i][0];
while (buff>0) {
characters.add('R');
buff--;
}
}
if(arr[i][1]-arr[i+1][1]<0){
int buff = arr[i+1][1]-arr[i][1];
while (buff>0) {
characters.add('U');
buff--;
}
}
}
if(flag){
System.out.println("YES");
for(int i=0;i<characters.size();i++){
System.out.print(characters.get(i));
}
System.out.println();
// System.out.println(characters);
}else {
System.out.println("NO");
}
t--;
}
}
}
| Java | ["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"] | 1 second | ["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"] | NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | Java 8 | standard input | [
"implementation",
"sortings"
] | b01c627abc00f97767c237e304f8c17f | The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) — the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$. | 1,200 | Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable. | standard output | |
PASSED | 494229d9c574c5723aa3b7dd2ba989ad | train_003.jsonl | 1579703700 | There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j < t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class CF1294_D2_B {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
solve(scanner);
}
}
private static void solve(Scanner scanner) {
int n = scanner.nextInt();
Point[] points = new Point[n];
for (int i = 0; i < n; i++) {
points[i] = new Point(scanner.nextInt(), scanner.nextInt());
}
Arrays.sort(points);
StringBuilder path = new StringBuilder();
goToPoint(new Point(0, 0), points[0], path);
Point current = points[0];
for (int i = 1; i < n; i++) {
if (current.y > points[i].y) {
System.out.println("NO");
return;
} else {
goToPoint(points[i - 1], points[i], path);
current.x = Math.max(current.x, points[i].x);
current.y = Math.max(current.y, points[i].y);
}
}
System.out.println("YES");
System.out.println(path);
// StringBuilder out = new StringBuilder();
// for (int j = 0; j < x[0]; j++) {
// out.append('R');
// }
// for (int j = 0; j < y[0]; j++) {
// out.append('U');
// }
// for (int i = 1; i < n; i++) {
// if (x[i] > x[i - 1]) {
// for (int j = 0; j < x[i] - x[i - 1]; j++) {
// out.append('R');
// }
// } else if (x[i] <)
// if (y[i] > y[i - 1])
// for (int j = 0; j < y[i] - y[i - 1]; j++) {
// out.append('U');
// }
// }
// System.out.println("YES");
// System.out.println(out);
}
private static void goToPoint(Point from, Point to, StringBuilder path) {
for (int i = 0; i < to.x - from.x; i++) {
path.append('R');
}
for (int i = 0; i < to.y - from.y; i++) {
path.append('U');
}
}
static class Point implements Comparable<Point> {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point point) {
if (point.x != x) {
return Integer.compare(x, point.x);
} else {
return Integer.compare(y, point.y);
}
}
@Override
public String toString() {
return String.format("(%d,%d)" , x , y);
}
}
}
| Java | ["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"] | 1 second | ["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"] | NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | Java 8 | standard input | [
"implementation",
"sortings"
] | b01c627abc00f97767c237e304f8c17f | The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) — the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$. | 1,200 | Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable. | standard output | |
PASSED | 61eba7ad28e5e67bd12147e607efad84 | train_003.jsonl | 1579703700 | There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j < t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way. | 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.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author binrodon
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int t = in.nextInt();
while (t > 0) {
int n = in.nextInt();
List<TaskB.Pair> packageList = new ArrayList<>();
for (int i = 0; i < n; i++) {
packageList.add(new TaskB.Pair(in.nextInt(), in.nextInt()));
}
Collections.sort(packageList);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < packageList.get(0).x; i++) sb.append("R");
for (int i = 0; i < packageList.get(0).y; i++) sb.append("U");
boolean isPackagesInOrder = true;
for (int i = 1; i < packageList.size(); i++) {
if (packageList.get(i).x - packageList.get(i - 1).x < 0
|| packageList.get(i).y - packageList.get(i - 1).y < 0) {
isPackagesInOrder = false;
break;
}
for (int k = 0; k < packageList.get(i).x - packageList.get(i - 1).x; k++) {
sb.append("R");
}
for (int k = 0; k < packageList.get(i).y - packageList.get(i - 1).y; k++) {
sb.append("U");
}
}
if (isPackagesInOrder) {
out.println("YES");
out.println(sb.toString());
} else {
out.println("NO");
}
t--;
}
}
private static class Pair implements Comparable<TaskB.Pair> {
int x;
int y;
public Pair(int a, int b) {
this.x = a;
this.y = b;
}
public boolean equals(Object o) {
TaskB.Pair p = (TaskB.Pair) o;
return this.x == p.x && this.y == p.y;
}
public int hashCode() {
int hash = 1;
hash = 89 * hash + this.x;
hash = 89 * hash + this.y;
return hash;
}
public int compareTo(TaskB.Pair o) {
return this.x == o.x ? this.y - o.y : this.x - o.x;
}
}
}
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 | ["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"] | 1 second | ["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"] | NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | Java 8 | standard input | [
"implementation",
"sortings"
] | b01c627abc00f97767c237e304f8c17f | The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) — the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$. | 1,200 | Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.