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
|
ba7a20b0c01b51de95e4bf569eb8dc79
|
train_001.jsonl
|
1550586900
|
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
|
256 megabytes
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class V1Q3 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
if(n==1){
int num=s.nextInt();
System.out.println("YES");
System.out.println(num);
return;
}
int[][] matrix;
Map<Integer,Integer> freq=new HashMap<>();
for (int i = 0; i <n*n ; i++) {
int num=s.nextInt();
if(freq.keySet().contains(num)){
freq.put(num,freq.get(num)+1);
}
else{
freq.put(num,1);
}
}
if(n%2==0){
matrix=new int[n/2][n/2];
int filled=0;
for (int num:freq.keySet()) {
if(freq.get(num)%4!=0){
System.out.println("NO");
return;
}
else{
int count=freq.get(num)/4;
for (int i = filled; i <filled+count ; i++) {
int row=i/(n/2);
int col=i%(n/2);
matrix[row][col]=num;
}
filled+=count;
}
}
System.out.println("YES");
// for (int i = 0; i <n/2 ; i++) {
// System.out.println(Arrays.toString(matrix[i]));
// }
printBoard(matrix,n);
}
else{
matrix=new int[n/2+1][n/2+1];
int set4=(n*n+1-2*n)/4;
int filled4=0;
int set2=n-1;
int filled2=0;
int set1=1;
for (int num:freq.keySet()) {
int f=freq.get(num);
int tset4=f/4;
int tset2=(f%4)/2;
if(f%2!=0){
set1--;
matrix[n/2][n/2]=num;
if(set1<0){
System.out.println("NO");
return;
}
if(f==1){
continue;
}
}
if(set4!=0){
int temp=set4;
int temp2=tset4;
set4=tset4<=set4?set4-tset4:0;
tset4=tset4<=temp?0:tset4-temp;
int count=temp2-tset4;
for (int i = filled4; i <filled4+count ; i++) {
int row=i/(n/2);
int col=i%(n/2);
matrix[row][col]=num;
}
filled4+=count;
}
if(tset4!=0) {
tset2 += 2 * tset4;
}
if(set2<tset2){
System.out.println("NO");
return;
}
else{
int temp=set2;
set2-=tset2;
int count=temp-set2;
for (int i = filled2; i <filled2+count ; i++) {
int row=i;
int col=n/2;
if(i>=n/2){
row=n/2;
col=i%(n/2);
}
matrix[row][col]=num;
}
filled2+=count;
}
}
System.out.println("YES");
// for (int i = 0; i <n/2+1 ; i++) {
// System.out.println(Arrays.toString(matrix[i]));
// }
printBoard(matrix,n);
}
}
private static void printBoard(int[][] matrix,int n) {
for (int i = 0; i <n ; i++) {
int i1=i;
if(i>=n/2){
i1=n-(i+1);
}
for (int j = 0; j <n ; j++) {
int j1=j;
if(j>=n/2){
j1=n-(j+1);
}
System.out.print(matrix[i1][j1]+" ");
}
System.out.println();
}
}
}
|
Java
|
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
|
2 seconds
|
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
|
NoteNote that there exist multiple answers for the first two examples.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
20928dd8e512bee2d86c6611c5e76390
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) β the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
| 1,700
|
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers β the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
|
standard output
| |
PASSED
|
36b02e98137dc2dffc0407c67b1bd3ef
|
train_001.jsonl
|
1550586900
|
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.io.*;
//import javafx.util.Pair;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.BitSet;
public class Prac{
public static void merge(int arr[], int l, int m, int r){
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
//ind[k][0]=i;
// ind[k][1]=dish[i];
// ind[k][2]=L[i];
i++;
}
else
{
arr[k] = R[j];
// ind[k][0]=j;
// ind[k][1]=dish[j];
// ind[k][2]=R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
// ind[k][0]=i;
// ind[k][1]=dish[i];
// ind[k][2]=L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
// ind[k][0]=j;
// ind[k][1]=dish[j];
// ind[k][2]=R[i];
j++;
k++;
}
}
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort(arr, l, m);
sort(arr , m+1, r);
merge(arr, l, m, r);
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
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[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String rs() {
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;
}
}
static PrintWriter w = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
InputReader sc=new InputReader(System.in);
//DecimalFormat df=new DecimalFormat("0.00000000000000000000");
//BigInteger b,max=BigInteger.ZERO;
//Scanner sc=new Scanner(System.in);
// HashMultiSet<Integer> multiSet = new HashMultiSet<>(new HashMap<>());
//findFact();
int n=sc.ni();
int arr[][]=new int[n+1][n+1];
int a[]=new int[1001];
boolean found=false;
int i=0,j=0;
for(i=0;i<n*n;i++)
a[sc.ni()]++;
if(n%2==0){
for(i=1;i<=1000;i++){
if(a[i]%4!=0){
found=true;
break;
}
}
if(found)
w.println("NO");
else{
w.println("YES");
i=1;
j=1;
for(int k=1;k<=1000;k++){
while(a[k]!=0){
arr[i][j]=k;
arr[i][n+1-j]=k;
arr[n+1-i][j]=k;
arr[n+1-i][n+1-j]=k;
i++;
if(i>n/2){
j++;
i=1;
}
a[k]-=4;
}
}
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
w.print(arr[i][j]+" ");
}
w.println();
}
}
}
else{
int one=0,two=0;
for(i=1;i<=1000;i++){
if(a[i]%2!=0){
arr[n/2+1][n/2+1]=i;
a[i]--;
one++;
}
if(a[i]%4==2){
two++;
}
if(one>1||two>(n/2)*2){
found=true;
break;
}
}
if(found)
w.println("NO");
else{
int count=n*n;
w.println("YES");
i=1;
j=1;
outer:
for(int k=1;k<=1000;k++){
while(a[k]>=4){
arr[i][j]=k;
arr[i][n+1-j]=k;
arr[n+1-i][j]=k;
arr[n+1-i][n+1-j]=k;
i++;
if(i>n/2){
j++;
i=1;
}
a[k]-=4;
count-=4;
if(count==2*n-1)
break outer;
}
}
i=1;
j=1;
outer:
for(int k=1;k<=1000;k++){
while(a[k]>=2){
arr[i][n/2+1]=k;
arr[n-i+1][n/2+1]=k;
i++;
a[k]-=2;
if(i==n/2+1)
break outer;
}
}
outer:
for(int k=1;k<=1000;k++){
while(a[k]>=2){
arr[n/2+1][j]=k;
arr[n/2+1][n-j+1]=k;
j++;
a[k]-=2;
if(j==n/2+1)
break outer;
}
}
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
w.print(arr[i][j]+" ");
}
w.println();
}
}
}
w.close();
}
}
|
Java
|
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
|
2 seconds
|
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
|
NoteNote that there exist multiple answers for the first two examples.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
20928dd8e512bee2d86c6611c5e76390
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) β the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
| 1,700
|
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers β the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
|
standard output
| |
PASSED
|
078115f703e2e35bc4ec2e5a99f9c419
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[256]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String args[])throws IOException{
Reader in = new Reader();
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = in.nextInt();
int[] s = new int[n];
s[0]=a[0];
for(int i=1;i<n;i++)
s[i]=s[i-1]+a[i];
int ans = 0;
for(int i=0;i<k;i++){
int l = in.nextInt()-1;
int r = in.nextInt()-1;
int x = 0;
if(l==0)
x=s[r];
else
x=s[r]-s[l-1];
if(x>0)
ans+=x;
}
System.out.println(ans);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
154fed7bb633e67b055fbff93c822c98
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int ar[] = new int[n+1];
int sum[] = new int[101];
sum[0] = 0;
for(int i=1; i<=n; i++){
ar[i]= sc.nextInt();
sum[i]=ar[i] +sum[i-1];
}
int ans=0;
for(int i=0; i<m; i++){
int l = sc.nextInt();
int r = sc.nextInt();
int tmp = sum[r] - sum[l-1];
if(tmp > 0) ans += tmp;
}
System.out.println(ans);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
f7c48765f55545bfd18d49f9542d208d
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Test{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[n+1];
for(int i=1;i<=n;i++)
arr[i] = sc.nextInt();
int answer = 0;
for(int i=0;i<m;i++){
int l = sc.nextInt();
int r = sc.nextInt();
int current = 0;
for(int j=l;j<=r;j++){
current+=arr[j];
}
if(current>0)
answer+=current;
}
System.out.println(answer);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
fda0fa9cdedbc439949d71ec3820c47e
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main2B {
static int n, m;
static int[] moods;
static int[] prefixSums;
public static void main(String[] args) throws IOException {
int total = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
moods = new int[n + 1];
prefixSums = new int[n + 1];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
moods[i + 1] = Integer.parseInt(st.nextToken());
prefixSums[i + 1] = prefixSums[i] + moods[i + 1];
}
for(int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int r = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken());
int diff = prefixSums[l] - prefixSums[r - 1];
if(diff > 0) total += diff;
}
System.out.println(total);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
6bc222d45c59ca8e60e1a911f832aa4a
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.util.Scanner;
/**
* Created by yuchzhou on 11/27/16.
*/
public class B {
int solve(int[] moods, int[][] subarrays) {
int sum = 0;
for (int[] subarray : subarrays) {
int subarraySum = 0;
for (int i = subarray[0]; i <= subarray[1]; ++i) {
subarraySum += moods[i - 1];
}
sum += Math.max(0, subarraySum);
}
return sum;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int[] moods = new int[n];
int[][] subarrays = new int[m][2];
for (int i = 0; i < n; ++i) {
moods[i] = s.nextInt();
}
for (int i = 0; i < m; ++i) {
subarrays[i][0] = s.nextInt();
subarrays[i][1] = s.nextInt();
}
System.out.println(new B().solve(moods, subarrays));
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
720e71fc2d909115fdf1a79665e99817
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class A {
static FastReader scan = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
Solver solver = new Solver();
int testCases = 1;
while (testCases--> 0) solver.solve();
out.close();
}
static class Solver {
void solve() {
int n = scan.nextInt(), m = scan.nextInt();
long ans = 0;
int[] a = scan.nextIntArray(n), pre = new int[n+1];
for(int i = 1; i <= n; i++) pre[i] = pre[i-1] + a[i-1];
for(int i = 0; i < m; i++) {
int l = scan.nextInt(), r = scan.nextInt();
int curr = pre[r] - pre[l-1];
if(curr > 0) ans += curr;
}
out.println(ans);
}
}
//Sathvik's Template Stuff BELOW!!!!!!!!!!!!!!!!!!!!!!
static class DSU {
int[] root, size;
int n;
DSU(int n) {
this.n = n;
root = new int[n];
size = new int[n];
for(int i = 0; i < n; i++) {
root[i] = i;
size[i] = 1;
}
}
int findParent(int idx) {
while(root[idx] != idx) {
root[idx] = root[root[idx]];
idx = root[idx];
}
return idx;
}
boolean union(int x, int y) {
int parX = findParent(x);
int parY = findParent(y);
if(parX == parY) return false;
if(size[parX] < size[parY]) {
root[parY] = parX;
size[parX] += size[parY];
} else {
root[parX] = parY;
size[parY] += size[parX];
}
return true;
}
}
static class Extra {
static void sort(int[] a) {
Integer[] aa = new Integer[a.length];
for (int i = 0; i < aa.length; i++) aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++) a[i] = aa[i];
}
static void sort(long[] a) {
Long[] aa = new Long[a.length];
for (int i = 0; i < aa.length; i++) aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++) a[i] = aa[i];
}
static void sort(double[] a) {
Double[] aa = new Double[a.length];
for (int i = 0; i < aa.length; i++) aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++) a[i] = aa[i];
}
static void sort(char[] a) {
Character[] aa = new Character[a.length];
for (int i = 0; i < aa.length; i++) aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++) a[i] = aa[i];
}
static long gcd(long a, long b) {
while(b > 0) {
long temp = b;
b = a%b;
a = temp;
}
return a;
}
static long lcm(long a, long b) {
return a * (b / gcd(a,b));
}
static boolean isPrime(long n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (long i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
static HashSet<Integer> sieve(int n) {
boolean[] prime = new boolean[n+1];
HashSet<Integer> res = new HashSet<>();
for(int p = 2; p*p <= n; p++) {
if(!prime[p]) {
res.add(p);
for(int i = p*p; i <= n; i+=p) prime[i] = true;
}
}
return res;
}
static HashMap<Long, Integer> primeFactorization(long n) {
HashMap<Long, Integer> res = new HashMap<>();
while(n % 2 == 0) {
res.put(2L, res.getOrDefault(2L, 0)+1);
n/=2;
}
for(long i = 3; i*i <= n; i+=2) {
while(n % i == 0) {
res.put(i, res.getOrDefault(i, 0)+1);
n/=i;
}
}
if(n > 2) res.put(n, 1);
return res;
}
}
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());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
5dda2dfa3fcd17fdf4004e26977c0ac3
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
//package com.dcomplex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int flowers[];
static BufferedReader getInput() {
return new BufferedReader(new InputStreamReader(System.in));
}
static void readInputs() throws IOException {
BufferedReader reader = getInput();
StringTokenizer t = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(t.nextToken());
int m = Integer.parseInt(t.nextToken());
flowers = new int[n];
// flowers
t = new StringTokenizer(reader.readLine());
for (int i=0; i<n; ++i) {
flowers[i] = Integer.parseInt(t.nextToken());
}
int res = 0;
for (int i=0; i<m; ++i) {
t = new StringTokenizer(reader.readLine());
int l = Integer.parseInt(t.nextToken())-1;
int r = Integer.parseInt(t.nextToken());
res += Math.max(0, calc(l, r));
}
System.out.println(res);
}
static int calc(int l, int r) {
int res = 0;
for (int i=l; i<r; ++i) {
res += flowers[i];
}
return res;
}
public static void main(String[] args) throws IOException {
readInputs();
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
67addb1ba3f4dcd5a62465cf45e5a3c4
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.util.HashMap;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String args[])
{
Reader sc=new Reader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.i();
int m=sc.i();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.i();
long ans=0;
while(m-->0)
{
int l=sc.i();
int r=sc.i();
l--;
long sum=0;
for(int i=l;i<r;i++)
sum+=arr[i];
ans+=Math.max(0,sum);
}
System.out.println(ans);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
a2f10a489c694fb8dad35cdd0540ed0a
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class codeforce {
static Scanner sc = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//static PrintStream out=new PrintStream(System.out);
public static int mod = 1000000007;
public static void main(String[] args) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
int mood=0;
for(int i=1;i<=m;i++){
int x=sc.nextInt()-1;int y=sc.nextInt()-1;
int sum=0;
for(int j=x;j<=y;j++)sum+=a[j];
if(sum>0)mood+=sum;
}
System.out.println(mood);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
b5227a150ce79867e8f010898d64c0be
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class alflow
{
public static void main(String args[])throws IOException
{
try
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(is);
String tokens[] = new String[2];
tokens = bf.readLine().split(" ");
int n = Integer.parseInt(tokens[0]);
int m = Integer.parseInt(tokens[1]);
String tokens1[] = new String[n];
tokens1 = bf.readLine().split(" ");
int arr[] = new int[n];
for(int i=0; i<n; i++)
{
arr[i] = Integer.parseInt(tokens1[i]);
}
int l[] = new int[m];
int r[] = new int[m];
for(int i=0; i<m; i++)
{
tokens = bf.readLine().split(" ");
l[i] = Integer.parseInt(tokens[0]);
r[i] = Integer.parseInt(tokens[1]);
}
int sum[] = new int[m];
for(int i=0; i<m; i++)
{
for(int j=l[i]-1; j<r[i]; j++)
{
sum[i]+=arr[j];
}
}
int output=0;
for(int i=0; i<m; i++)
{
if(sum[i]>0)
{
output+=sum[i];
}
}
System.out.println(output);
}catch(Exception e)
{
return;
}
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
9b0acb048ac89030b222d39424ed4816
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.*;
import java.text.*;
import java.util.*;
public class B {
public static void main(String[] args) throws Exception {
new B().run();
}
public void run() throws Exception {
FastScanner f = new FastScanner();
int n = f.nextInt(), m = f.nextInt();
long[][] sums = new long[n][n];
for(int i = 0; i < n; i++) {
int flower = f.nextInt();
sums[i][i] = flower;
for(int j = 0; j < i; j++) sums[j][i] = flower + sums[j][i-1];
}
long total = 0;
while(m-->0) {
long sum = sums[f.nextInt()-1][f.nextInt()-1];
if(sum > 0) total += sum;
}
System.out.println(total);
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
fe8c875d337b095c59cfe443ed0e4f64
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.util.Scanner;
public class Class740B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int x[] = new int[a];
int z[][] = new int[b][2];
for (int i = 0; i < a; i++) {
x[i] = sc.nextInt();
}
for (int i = 0; i < b; i++) {
for (int j = 0; j < 2; j++) {
z[i][j] = sc.nextInt() - 1;
}
}
long sum = 0;
int y[] = new int[b];
for (int i = 0; i < b; i++) {
y[i] = 0;
for (int j = z[i][0]; j <= z[i][1]; j++) {
y[i] += x[j];
}
}
for (int i = 0; i < b; i++) {
if (y[i] > 0) {
sum += y[i];
}
}
System.out.println(sum);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
c0d8605b5b7e2024daf2183f816120af
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.util.Scanner;
public class alyona
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int count=0;
for(int i=0;i<m;i++)
{
int l=sc.nextInt();
int r=sc.nextInt();
l=l-1;
int s=0;
for(int j=l;j<r;j++)
{
s=s+a[j];
}
if(s>0)
count=count+s;
}
System.out.println(count);
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
20d21f26c36a4a84c4b747668e8d8745
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class CodeForces {
private final BufferedReader reader;
private final PrintWriter writer;
private StringTokenizer tokenizer;
private void solve() {
int n = nextInt();
int m = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
long[] sums = new long[m];
int l, r;
for (int i = 0; i < m; i++) {
l = nextInt() - 1;
r = nextInt() - 1;
for (int j = l; j <= r; j++) {
sums[i] += a[j];
}
}
long res = 0;
for (int i = 0; i < m; i++) {
if (sums[i] > 0) res += sums[i];
}
writer.print(res);
}
public static void main(String[] args) {
new CodeForces(System.in, System.out);
}
private CodeForces(InputStream inputStream, OutputStream outputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.writer = new PrintWriter(outputStream);
solve();
writer.close();
}
private String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
private String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
private int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private double nextDouble() {
return Double.parseDouble(next());
}
public boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = readLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
private int upperBinary(long[] array, long key) {
int low = 0;
int high = array.length - 1;
if (high < 0) return -1;
while (low < high) {
int mid = (low + high + 1) >>> 1;
if (array[mid] <= key) low = mid;
else high = mid - 1;
}
if (array[low] != key) {
if (array[low] < key) low++;
low = -(low + 1);
}
return low;
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
7d06f3c0189fdd6852bf24b4c455bac8
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import javax.management.Query;
import com.sun.org.apache.bcel.internal.generic.SWAP;
public class fstclass {
static int[] a = new int[10000100];
public static void main(String[] args) {
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
int n, m, i, j;
long[] a = new long[1000];
n = in.nextInt();
m = in.nextInt();
for(i = 1; i <= n; i ++)
a[i] = in.nextInt();
int ans = 0;
for(i = 1; i <= m; i ++) {
int l = in.nextInt();
int r = in.nextInt();
int s = 0;
for(j = l; j <= r; j ++) {
s += a[j];
}
if(s > 0)
ans += s;
}
System.out.print(ans);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
98da9c15ff45abb47b9923746fd4cb7e
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Mehul Sharma
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[] flowers = new int[n + 1];
for (int i = 1; i <= n; i++) {
flowers[i] = in.nextInt();
}
int[] momsuggestions = new int[m];
for (int i = 0; i < m; i++) {
int start = in.nextInt();
int end = in.nextInt();
for (int j = start; j <= end; j++) {
momsuggestions[i] += flowers[j];
}
}
int max = 0;
for (int i = 0; i < m; i++) {
if (momsuggestions[i] > 0) {
max += momsuggestions[i];
}
}
System.out.print(max);
}
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
032b3d714b68dafa0311e48fa1fe4fb3
|
train_001.jsonl
|
1479918900
|
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,ββ-β2,β1,β3,ββ-β4. Suppose the mother suggested subarrays (1,ββ-β2), (3,ββ-β4), (1,β3), (1,ββ-β2,β1,β3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1Β·1β=β1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (β-β2)Β·1β=ββ-β2, because he is in one of chosen subarrays, the third flower adds 1Β·2β=β2, because he is in two of chosen subarrays, the fourth flower adds 3Β·2β=β6, because he is in two of chosen subarrays, the fifth flower adds (β-β4)Β·0β=β0, because he is in no chosen subarrays. Thus, in total 1β+β(β-β2)β+β2β+β6β+β0β=β7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
|
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.Arrays;
import java.util.StringTokenizer;
public class B381 {
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(1, in, out);
out.close();
}
private static void solve(int n, InputReader in, PrintWriter out) {
while (n > 0) {
solve(in, out);
n--;
}
}
private static void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int a[] = new int[n];
for(int i = 0; i< n; i++){
a[i] = in.nextInt();
}
int interval[][] = new int[m][3];
for(int i = 0; i < m; i++){
interval[i][0] = in.nextInt();
interval[i][1] = in.nextInt();
}
int left[] = new int[n];
left[0] = a[0];
for(int i = 1; i< n; i++){
left[i] = left[i-1] + a[i];
}
int count[] = new int[n];
Arrays.fill(count, 0);
for(int i = 0; i< m; i++){
interval[i][2] = left[interval[i][1]-1] - left[interval[i][0]-1] + a[interval[i][0]-1];
if(interval[i][2] > 0) {
for(int j = interval[i][0]-1; j<= interval[i][1]-1; j++){
count[j]++;
}
}
}
int result = 0;
for(int i = 0; i < n; i++){
result += a[i] * count[i];
}
System.out.println(result);
}
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 String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"]
|
2 seconds
|
["7", "16", "0"]
|
NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.
|
Java 8
|
standard input
|
[
"constructive algorithms"
] |
6d7364048428c70e0e9b76ab1eb8cc34
|
The first line contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moodsΒ β n integers a1,βa2,β...,βan (β-β100ββ€βaiββ€β100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1ββ€βliββ€βriββ€βn) denoting the subarray a[li],βa[liβ+β1],β...,βa[ri]. Each subarray can encounter more than once.
| 1,200
|
Print single integerΒ β the maximum possible value added to the Alyona's happiness.
|
standard output
| |
PASSED
|
c81baa1d5c73348406b2f15f11f3430c
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution implements Runnable
{
static class InputReader
{
private InputStream stream;private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream){this.stream = stream;}
public int read(){if (numChars==-1) throw new InputMismatchException();if (curChar >= numChars){curChar = 0;try{numChars = stream.read(buf);}catch (IOException e){throw new InputMismatchException(); }if(numChars <= 0)return -1;}return buf[curChar++];}
public String nextLine(){String str = "";try{str = br.readLine();}catch (IOException e){e.printStackTrace();}return str;}
public int nextInt(){int c = read(); while(isSpaceChar(c))c = read(); int sgn = 1; if (c == '-'){sgn = -1;c = read(); }int res = 0;do{if(c<'0'||c>'9') throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public long nextLong(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}long res = 0;do{if (c < '0' || c > '9')throw new InputMismatchException();res *= 10;res += c - '0';c = read();}while (!isSpaceChar(c));return res * sgn;}
public double nextDouble(){int c = read();while (isSpaceChar(c))c = read();int sgn = 1;if (c == '-'){sgn = -1;c = read();}double res = 0;while (!isSpaceChar(c) && c != '.'){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')
throw new InputMismatchException();res *= 10;res += c - '0';c = read();}if (c == '.'){c = read();double m = 1;while (!isSpaceChar(c)){if (c == 'e' || c == 'E')return res * Math.pow(10, nextInt());if (c < '0' || c > '9')throw new InputMismatchException();m /= 10;res += (c - '0') * m;c = read();}}return res * sgn;}
public String readString(){int c = read();while (isSpaceChar(c))c = read();StringBuilder res = new StringBuilder();do{res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public boolean isSpaceChar(int c){if (filter != null)return filter.isSpaceChar(c);return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;}
public String next(){return readString();}
public interface SpaceCharFilter{public boolean isSpaceChar(int ch);}
}
public static void main(String args[]) throws Exception{new Thread(null, new Solution(),"Main",1<<27).start();}
public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a);}
public static long findGCD(long arr[], int n) { long result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result);return result; }
static void sortbycolomn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,final int[] entry2) {
if (entry1[col] > entry2[col])return 1;
else return -1;
}
});
}
static void dfs(int i,ArrayList<Integer>[] arr,int[] visited,int[][] sp){
visited[i]=1;
for(int j=0;j<arr[i].size();j++){
int x=arr[i].get(j);
if(visited[x]==0){
sp[x][0]=sp[i][0]+1;
dfs(x,arr,visited,sp);
}
}
for(int j=0;j<arr[i].size();j++){
int x=arr[i].get(j);
if(sp[i][0]<sp[x][0])
sp[i][1]+=sp[x][1];
}
}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=in.nextInt();
int k=in.nextInt();
ArrayList<Integer>[] arr=new ArrayList[n+1];
for(int i=0;i<=n;i++){
arr[i]=new ArrayList<>();
}
int x=0;
int y=0;
for(int i=0;i<n-1;i++){
x=in.nextInt();
y=in.nextInt();
arr[x].add(y);
arr[y].add(x);
}
int[][] sp=new int[n+1][2];
for(int i=1;i<n+1;i++)
sp[i][1]=1;
int[] visited=new int[n+1];
dfs(1,arr,visited,sp);
ArrayList<Integer> ans=new ArrayList<>();
for(int i=1;i<=n;i++)
ans.add(sp[i][0]-sp[i][1]+1);
Collections.sort(ans);
long sum=0;
for(int i=n-1;k>0 && i>=0;i--,k--)
sum=(long)(sum+ans.get(i));
w.println(sum);
w.flush();
w.close();
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
147d646f79c83a62bb0553b2f6d68760
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.InputMismatchException;
public class CFB {
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
InputStream stream = System.in;
Logger logger = new Logger();
if (args.length>1 && args[0].equals("LOCAL") && args[1].equals("YES")) {
File inputFile = new File("resources/input.in");
stream = new DataInputStream(new FileInputStream(inputFile));
logger.enableLogging(true, "resources/logs.txt");
}
InputReader in = new InputReader(stream);
PrintWriter out = new PrintWriter(System.out);
Thread th = new Thread(null, () -> new Task1().solve(in, out, logger), "Task1", 1 << 25);
th.start();
th.join();
out.close();
logger.close();
}
static class Node implements Comparable<Node> {
Integer index, depth, size;
public Node(int index, int depth, int size) {
this.index = index;
this.depth = depth;
this.size = size;
}
@Override
public int compareTo(Node o) {
int c = (depth - size) - (o.depth - o.size);
if (c == 0) {
return index.compareTo(o.index);
}
return c;
}
@Override
public String toString() {
return "("+index+","+depth+","+size+")";
}
}
static class Task1 {
ArrayList<Integer>[] adj;
int[] depth, subtreeSize;
boolean[] industry;
int[] count;
void solve(InputReader in, PrintWriter out, Logger logger) {
int n = in.nextInt(), k = in.nextInt();
depth = new int[n];
subtreeSize = new int[n];
adj = new ArrayList[n];
for (int i=0; i<n; i++) {
adj[i] = new ArrayList<>();
}
for (int i=1; i<n; i++) {
int u = in.nextInt()-1, v = in.nextInt()-1;
adj[u].add(v);
adj[v].add(u);
}
calculateDepthAndSize(0, 0);
Node[] nodes = new Node[n];
for (int i=0; i<n; i++) {
nodes[i] = new Node(i, depth[i], subtreeSize[i]);
}
Arrays.sort(nodes, Collections.reverseOrder());
industry = new boolean[n];
count = new int[n];
for (int i=0; i<k; i++) {
industry[nodes[i].index] = true;
}
calculateIndustry(0, 0);
// logger.logln("depth:"+Arrays.toString(depth));
// logger.logln("size:"+Arrays.toString(subtreeSize));
// logger.logln("nodes:"+Arrays.toString(nodes));
// logger.logln("industries:"+Arrays.toString(industry));
// logger.logln("count:"+Arrays.toString(count));
long ans = 0;
for (int i=0; i<n; i++) {
if (!industry[i]) {
ans += count[i];
}
}
out.println(ans);
}
int calculateIndustry(int v, int p) {
int cnt = 0;
if (industry[v]) { cnt++; }
for (int w: adj[v]) {
if (w != p) {
cnt += calculateIndustry(w, v);
}
}
return count[v] = cnt;
}
int calculateDepthAndSize(int v, int p) {
depth[v] = depth[p]+1;
if (adj[v].size()==1 && adj[v].get(0)==p) {
return subtreeSize[v] = 1;
}
int size = 1;
for (int w: adj[v]) {
if (w!=p) {
size += calculateDepthAndSize(w, v);
}
}
return subtreeSize[v] = size;
}
int lowerBound(long[] a, int lo, long key) { // first element not less than key
int hi=a.length-1;
while(hi>=lo) {
int mid = (lo+hi)>>1;
if(a[mid] < key) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return lo;
}
}
static class Logger {
private PrintWriter logger;
private boolean loggingEnabled;
void enableLogging(boolean enable, String filename) {
this.loggingEnabled = enable;
try {
if (loggingEnabled) this.logger = new PrintWriter(filename);
} catch (FileNotFoundException ignored) {
}
}
void log(Object s) {
if (loggingEnabled) {
logger.print(s.toString());
}
}
void logln(Object s) {
if (loggingEnabled) {
logger.println(s.toString());
}
}
void close() {
if (loggingEnabled) logger.close();
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, numChars;
private SpaceCharFilter filter;
InputReader(InputStream stream) {
this.stream = stream;
}
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++];
}
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;
}
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;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
bdab38b66563b6d66d00ce4d7849df13
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
private static int n, k;
private static City[] cities;
private static ArrayList<ArrayList<Integer>> edges;
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String[] input = in.readLine().split("\\s+");
n = Integer.parseInt(input[0]);
k = Integer.parseInt(input[1]);
cities = new City[n];
edges = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < n; i++) {
cities[i] = new City(i, Integer.MAX_VALUE);
edges.add(new ArrayList<Integer>());
}
for (int i = 0; i < n - 1; i++) {
input = in.readLine().split("\\s+");
int u = Integer.parseInt(input[0]) - 1;
int v = Integer.parseInt(input[1]) - 1;
edges.get(u).add(v);
edges.get(v).add(u);
}
out.println(solve());
in.close();
out.close();
}
private static long solve() {
dfs(0, 0);
Arrays.sort(cities);
long ans = 0;
for (int i = 0; i < k; i++) {
ans += cities[i].dist - cities[i].children;
}
return ans;
}
private static int dfs(int u, int d) {
cities[u].dist = d;
for (int v: edges.get(u)) {
if (cities[v].dist == Integer.MAX_VALUE) {
cities[u].children += dfs(v, d + 1);
}
}
return cities[u].children + 1;
}
}
class City implements Comparable<City> {
int id;
int dist;
int children;
public City(int id, int dist) {
this.id = id;
this.dist = dist;
this.children = 0;
}
public int compareTo(City c) {
return -1 * Integer.compare(this.dist - this.children, c.dist - c.children);
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
19ff7de94b54c4ecbdbe0e1047c5cd84
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class R635C_Post {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
StringTokenizer tok=new StringTokenizer(in.readLine());
int N=Integer.parseInt(tok.nextToken()),
K=Integer.parseInt(tok.nextToken());
neighbors=new ArrayList<>();
for (int i=0; i<N; i++)
neighbors.add(new ArrayList<>());
for (int i=0; i<N-1; i++) {
tok=new StringTokenizer(in.readLine());
int u=Integer.parseInt(tok.nextToken())-1,
v=Integer.parseInt(tok.nextToken())-1;
neighbors.get(u).add(v);
neighbors.get(v).add(u);
}
seen=new boolean[N];
depth=new int[N];
depth[0]=0;
par=new int[N];
par[0]=-1;
sz=new int[N];
dfs(0);
//place vert -> SUM(happiness)+=depth[vert]-#industry verts in subtree(vert)
//greedy?
boolean[] heavy=new boolean[N], has_heavy_child=new boolean[N];
for (int v=0; v<N; v++)
if (neighbors.get(v).size()>1) {
int bc=-1, bsz=-1;
for (int n:neighbors.get(v))
if (n!=par[v] && sz[n]>bsz) {
bsz=sz[n];
bc=n;
}
heavy[bc]=true;
has_heavy_child[v]=true;
}
int[] path_id=new int[N], pos=new int[N];
Arrays.fill(path_id,-1);
Arrays.fill(pos,-1);
//List<Segtree> trees=new ArrayList<>();
List<List<Integer>> paths=new ArrayList<>();
for (int v=0; v<N; v++) {
if (!has_heavy_child[v]) {
if (path_id[v]!=-1)
throw new RuntimeException();
int p=v;
while (heavy[p])
p=par[p];
List<Integer> path=new ArrayList<>();
for (int i=v; i!=par[p]; i=par[i]) {
pos[i]=path.size();
path.add(i);
if (path_id[i]!=-1) throw new RuntimeException();
path_id[i] = paths.size();
}
paths.add(path);
/*Segtree t=new Segtree(v,p);
for (int i=0; i<path.size(); i++)
t.add(i,i,depth[path.get(i)]);*/
//trees.add(t);
}
}
int[] loc_v=new int[N], v_loc=new int[N];
for (int pi=0, id=0; pi<paths.size(); pi++)
for (int v:paths.get(pi)) {
loc_v[id]=v;
v_loc[v]=id;
id++;
}
Segtree tree=new Segtree(N); //tree[i]=score of vertex verts_ord[i]
for (int i=0; i<N; i++)
tree.add(i,i,depth[loc_v[i]]);
long tscr=0;
boolean[] open=new boolean[N];
Arrays.fill(open,true);
for (int $=0; $<K; $++) {
int[] bi=tree.max(0,N-1);
tscr+=bi[0];
tree.add(bi[1],bi[1],-1000_000_000);
if (!open[loc_v[bi[1]]]) throw new RuntimeException();
open[loc_v[bi[1]]]=false;
for (int v=loc_v[bi[1]]; v>-1;) {
List<Integer> p=paths.get(path_id[v]);
tree.add(v_loc[v],v_loc[p.get(p.size()-1)],-1);
v=par[p.get(p.size()-1)];
}
}
/*for (int $=0; $<K; $++) {
int[] binfo=null;
int bti=-1;
//vvv TOO SLOW
//could either create segtree of segtrees or just merge all segtrees into one segtree (ea. path is a contiguous subarray)
for (int ti=0; ti<trees.size(); ti++) {
Segtree t=trees.get(ti);
int[] info=t.max(0,t.N-1);
if (binfo==null || info[0]>binfo[0]) {
bti=ti;
binfo=info;
}
}
trees.get(bti).add(binfo[1],binfo[1],-1000_000_000);
if (!open[paths.get(bti).get(binfo[1])]) throw new RuntimeException();
open[paths.get(bti).get(binfo[1])]=false;
tscr+=binfo[0];
trees.get(bti).add(binfo[1],paths.get(bti).size()-1,-1);
for (int v=par[trees.get(bti).high]; v>-1; v=par[trees.get(path_id[v]).high])
trees.get(path_id[v]).add(pos[v],paths.get(path_id[v]).size()-1,-1);
}*/
System.out.println(tscr);
}
private static class Segtree {
//range add update, range max/loc query
private int low, high;
private int N;
private int[][] vert;
private int[] upd;
public Segtree(int N) {
this.low=this.high=-1;
this.N=N;
vert=new int[4*N][];
upd=new int[4*N];
build(0,0,N-1);
}
public Segtree(int lo, int hi) {
this.low=lo;
this.high=hi;
this.N=depth[lo]-depth[hi]+1;
vert=new int[4*N][];
upd=new int[4*N];
build(0,0,N-1);
}
private void build(int id, int l, int r) {
vert[id]=new int[] {0,l};
if (l<r) {
int m=(l+r)/2;
build(2*id+1,l,m);
build(2*id+2,m+1,r);
}
}
private void push(int id, int l, int r) {
int u=upd[id];
if (u==0)
return;
vert[id][0]+=u;
if (l<r) {
upd[2*id+1]+=u;
upd[2*id+2]+=u;
}
upd[id]=0;
}
private void add(int id, int l, int r, int i, int j, int v) {
push(id,l,r);
if (i<=l && r<=j) {
upd[id]=v;
push(id,l,r);
}
else if (i<=r && l<=j) {
int m=(l+r)/2;
add(2*id+1,l,m,i,j,v);
add(2*id+2,m+1,r,i,j,v);
if (vert[2*id+2][0]>vert[2*id+1][0]) {
vert[id][0]=vert[2*id+2][0];
vert[id][1]=vert[2*id+2][1];
}
else {
vert[id][0]=vert[2*id+1][0];
vert[id][1]=vert[2*id+1][1];
}
}
}
private int[] max(int id, int l, int r, int i, int j) {
push(id,l,r);
if (i<=l && r<=j)
return vert[id].clone();
else if (i<=r && l<=j) {
int m=(l+r)/2;
int[] L=max(2*id+1,l,m,i,j),
R=max(2*id+2,m+1,r,i,j);
return R[0]>L[0]?R:L;
}
else
return new int[] {Integer.MIN_VALUE,-1};
}
public void add(int i, int j, int v) {
add(0,0,N-1,i,j,v);
}
public int[] max(int i, int j) {
return max(0,0,N-1,i,j);
}
}
private static boolean[] seen;
private static int[] depth, par, sz;
private static List<List<Integer>> neighbors;
private static void dfs(int i) {
seen[i]=true;
sz[i]=1;
for (int n:neighbors.get(i)) {
if (!seen[n]) {
par[n]=i;
depth[n]=depth[i]+1;
dfs(n);
sz[i]+=sz[n];
}
}
}
}
//using submission 77023418, only replacing definition of a heavy edge
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
917fdc41d0250873277511f3a49547d8
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class R635C_Post {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok=new StringTokenizer(in.readLine());
int N=Integer.parseInt(tok.nextToken()),
K=Integer.parseInt(tok.nextToken());
/*int[][] edges=new int[N-1][2];
int[] deg=new int[N];*/
neighbors=new ArrayList<>();
for (int i=0; i<N; i++)
neighbors.add(new ArrayList<>());
for (int i=0; i<N-1; i++) {
tok = new StringTokenizer(in.readLine());
int u = Integer.parseInt(tok.nextToken()) - 1,
v = Integer.parseInt(tok.nextToken()) - 1;
neighbors.get(u).add(v);
neighbors.get(v).add(u);
/*edges[i][0] = u;
edges[i][1] = v;
deg[u]++;
deg[v]++;*/
}
/*neighbors=new int[N][];
for (int i=0; i<N; i++)
neighbors[i]=new int[deg[i]];
int[] idxs=new int[N];
for (int[] e:edges) {
int u=e[0], v=e[1];
neighbors[u][idxs[u]++]=v;
neighbors[v][idxs[v]++]=u;
}*/
seen=new boolean[N];
depth=new int[N];
depth[0]=0;
par=new int[N];
par[0]=-1;
sz=new int[N];
dfs(0);
//place vert -> SUM(happiness)+=depth[vert]-#industry verts in subtree(vert)
boolean[] heavy=new boolean[N], has_heavy_child=new boolean[N];
/*heavy[0]=false;
for (int i=1; i<N; i++)
if (2*sz[i] >= sz[par[i]])
heavy[i] =has_heavy_child[par[i]] = true;*/
//vvvv choosing child w/ largest subtree to have heavy edge
//MUCH BETTER than choosing child w/ subtree size >=(sz[v]/2.0) (maybe bc. it creates fewer paths)
for (int v=0; v<N; v++)
if (neighbors.get(v).size()>1) {
int bc=-1, bsz=-1;
for (int n:neighbors.get(v))
if (n!=par[v] && sz[n]>bsz) {
bsz=sz[n];
bc=n;
}
heavy[bc]=true;
has_heavy_child[v]=true;
}
//System.out.println(Arrays.toString(heavy)+"\n"+Arrays.toString(has_heavy_child));
int[] path_end=new int[N];
int[] loc_v=new int[N], v_loc=new int[N];
for (int v=0, id=0; v<N; v++) {
if (!has_heavy_child[v]) {
int p=v;
while (heavy[p])
p=par[p];
for (int i=v; i!=par[p]; i=par[i]) {
path_end[i] = p;
loc_v[id]=i;
v_loc[i]=id;
id++;
}
}
}
int[] init=new int[N];
for (int i=0; i<N; i++)
init[i]=depth[loc_v[i]];
Segtree tree=new Segtree(init); //added proper segtree initialization
long tscr=0;
for (int $=0; $<K; $++) {
int[] bi=tree.max(0,N-1);
tscr+=bi[0];
tree.add(bi[1],bi[1],-1000_000_000);
for (int v=loc_v[bi[1]]; v>-1;) {
int en=path_end[v];
tree.add(v_loc[v],v_loc[en],-1);
v=par[en];
}
}
System.out.println(tscr);
}
private static class Segtree {
//range add update, range max/loc query
private int N;
private int[][] vert;
private int[] upd;
public Segtree(int[] a) {
this.N=a.length;
vert=new int[4*N][];
upd=new int[4*N];
build(0,0,N-1,a);
}
private void build(int id, int l, int r, int[] a) {
if (l==r)
vert[id]=new int[] {a[l],l};
else {
int m=(l+r)/2;
build(2*id+1,l,m,a);
build(2*id+2,m+1,r,a);
vert[id]=new int[2];
children_update(id);
}
}
private void children_update(int id) {
if (vert[2*id+2][0]>vert[2*id+1][0]) {
vert[id][0]=vert[2*id+2][0];
vert[id][1]=vert[2*id+2][1];
}
else {
vert[id][0]=vert[2*id+1][0];
vert[id][1]=vert[2*id+1][1];
}
}
private void push(int id, int l, int r) {
int u=upd[id];
if (u==0)
return;
vert[id][0]+=u;
if (l<r) {
upd[2*id+1]+=u;
upd[2*id+2]+=u;
}
upd[id]=0;
}
private void add(int id, int l, int r, int i, int j, int v) {
push(id,l,r);
if (i<=l && r<=j) {
upd[id]=v;
push(id,l,r);
}
else if (i<=r && l<=j) {
int m=(l+r)/2;
add(2*id+1,l,m,i,j,v);
add(2*id+2,m+1,r,i,j,v);
children_update(id);
}
}
private int[] max(int id, int l, int r, int i, int j) {
push(id,l,r);
if (i<=l && r<=j)
return vert[id].clone();
else if (i<=r && l<=j) {
int m=(l+r)/2;
int[] L=max(2*id+1,l,m,i,j),
R=max(2*id+2,m+1,r,i,j);
return R[0]>L[0]?R:L;
}
else
return new int[] {Integer.MIN_VALUE,-1};
}
public void add(int i, int j, int v) {
add(0,0,N-1,i,j,v);
}
public int[] max(int i, int j) {
return max(0,0,N-1,i,j);
}
}
private static boolean[] seen;
private static int[] depth, par, sz;
private static List<List<Integer>> neighbors;
private static void dfs(int i) {
seen[i]=true;
sz[i]=1;
for (int n:neighbors.get(i)) {
if (!seen[n]) {
par[n]=i;
depth[n]=depth[i]+1;
dfs(n);
sz[i]+=sz[n];
}
}
}
}
//can you use slower but easier-to-implement way of storing tree graph?
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
b878ae69a6feac5ba26ff11a40f9d6b1
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class R635C_Post {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok=new StringTokenizer(in.readLine());
int N=Integer.parseInt(tok.nextToken()),
K=Integer.parseInt(tok.nextToken());
int[][] edges=new int[N-1][2];
int[] deg=new int[N];
for (int i=0; i<N-1; i++) {
tok = new StringTokenizer(in.readLine());
int u = Integer.parseInt(tok.nextToken()) - 1,
v = Integer.parseInt(tok.nextToken()) - 1;
edges[i][0] = u;
edges[i][1] = v;
deg[u]++;
deg[v]++;
}
neighbors=new int[N][];
for (int i=0; i<N; i++)
neighbors[i]=new int[deg[i]];
int[] idxs=new int[N];
for (int[] e:edges) {
int u=e[0], v=e[1];
neighbors[u][idxs[u]++]=v;
neighbors[v][idxs[v]++]=u;
}
seen=new boolean[N];
depth=new int[N];
depth[0]=0;
par=new int[N];
par[0]=-1;
sz=new int[N];
dfs(0);
//place vert -> SUM(happiness)+=depth[vert]-#industry verts in subtree(vert)
boolean[] heavy=new boolean[N], has_heavy_child=new boolean[N];
/*heavy[0]=false;
for (int i=1; i<N; i++)
if (2*sz[i] >= sz[par[i]])
heavy[i] =has_heavy_child[par[i]] = true;*/
for (int v=0; v<N; v++)
if (neighbors[v].length>1) {
int bc=-1, bsz=-1;
for (int n:neighbors[v])
if (n!=par[v] && sz[n]>bsz) {
bsz=sz[n];
bc=n;
}
heavy[bc]=true;
has_heavy_child[v]=true;
}
//System.out.println(Arrays.toString(heavy)+"\n"+Arrays.toString(has_heavy_child));
int[] path_end=new int[N];
int[] loc_v=new int[N], v_loc=new int[N];
for (int v=0, id=0; v<N; v++) {
if (!has_heavy_child[v]) {
int p=v;
while (heavy[p])
p=par[p];
for (int i=v; i!=par[p]; i=par[i]) {
path_end[i] = p;
loc_v[id]=i;
v_loc[i]=id;
id++;
}
}
}
int[] init=new int[N];
for (int i=0; i<N; i++)
init[i]=depth[loc_v[i]];
Segtree tree=new Segtree(init); //added proper segtree initialization
long tscr=0;
for (int $=0; $<K; $++) {
int[] bi=tree.max(0,N-1);
tscr+=bi[0];
tree.add(bi[1],bi[1],-1000_000_000);
for (int v=loc_v[bi[1]]; v>-1;) {
int en=path_end[v];
tree.add(v_loc[v],v_loc[en],-1);
v=par[en];
}
}
System.out.println(tscr);
}
private static class Segtree {
//range add update, range max/loc query
private int N;
private int[][] vert;
private int[] upd;
public Segtree(int[] a) {
this.N=a.length;
vert=new int[4*N][];
upd=new int[4*N];
build(0,0,N-1,a);
}
private void build(int id, int l, int r, int[] a) {
if (l==r)
vert[id]=new int[] {a[l],l};
else {
int m=(l+r)/2;
build(2*id+1,l,m,a);
build(2*id+2,m+1,r,a);
vert[id]=new int[2];
children_update(id);
}
}
private void children_update(int id) {
if (vert[2*id+2][0]>vert[2*id+1][0]) {
vert[id][0]=vert[2*id+2][0];
vert[id][1]=vert[2*id+2][1];
}
else {
vert[id][0]=vert[2*id+1][0];
vert[id][1]=vert[2*id+1][1];
}
}
private void push(int id, int l, int r) {
int u=upd[id];
if (u==0)
return;
vert[id][0]+=u;
if (l<r) {
upd[2*id+1]+=u;
upd[2*id+2]+=u;
}
upd[id]=0;
}
private void add(int id, int l, int r, int i, int j, int v) {
push(id,l,r);
if (i<=l && r<=j) {
upd[id]=v;
push(id,l,r);
}
else if (i<=r && l<=j) {
int m=(l+r)/2;
add(2*id+1,l,m,i,j,v);
add(2*id+2,m+1,r,i,j,v);
children_update(id);
}
}
private int[] max(int id, int l, int r, int i, int j) {
push(id,l,r);
if (i<=l && r<=j)
return vert[id].clone();
else if (i<=r && l<=j) {
int m=(l+r)/2;
int[] L=max(2*id+1,l,m,i,j),
R=max(2*id+2,m+1,r,i,j);
return R[0]>L[0]?R:L;
}
else
return new int[] {Integer.MIN_VALUE,-1};
}
public void add(int i, int j, int v) {
add(0,0,N-1,i,j,v);
}
public int[] max(int i, int j) {
return max(0,0,N-1,i,j);
}
}
private static boolean[] seen;
private static int[] depth, par, sz;
private static int[][] neighbors;
private static void dfs(int i) {
seen[i]=true;
sz[i]=1;
for (int n:neighbors[i]) {
if (!seen[n]) {
par[n]=i;
depth[n]=depth[i]+1;
dfs(n);
sz[i]+=sz[n];
}
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
c3f36730f416ef18acda920aee0ee18f
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
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.HashMap;
import java.util.StringTokenizer;
public class q3 {
static int depth = 0;
public static void main(String[] args) {
FastReader s = new FastReader();
int n = s.nextInt();
int k = s.nextInt();
HashMap<Integer,ArrayList<Integer>> map = new HashMap<>();
for(int i=0;i<n-1;++i)
{
int n1 = s.nextInt();
int n2 = s.nextInt();
ArrayList<Integer> child;
if(map.containsKey(n1))
{
child = map.get(n1);
child.add(n2);
}
else {
child = new ArrayList<>();
child.add(n2);
map.put(n1, child);
}
if(map.containsKey(n2))
{
child = map.get(n2);
child.add(n1);
}
else {
child = new ArrayList<>();
child.add(n1);
map.put(n2, child);
}
}
depth = 0;
int[] ans = new int[n+1];
int[] visited = new int[n+1];
dfs(map,ans,1,visited);
ans[0] = Integer.MIN_VALUE;
Arrays.sort(ans);
long fans = 0;
for(int i=n;i>n-k;--i)
{
fans += ans[i];
}
System.out.println(fans);
}
private static int dfs(HashMap<Integer,ArrayList<Integer>> map, int[] ans,int currN,int[] visited) {
int size = 0;
visited[currN] = 1;
ArrayList<Integer> child = map.get(currN);
if(child != null)
{
for(int i=0;i<child.size();++i)
{
if(visited[child.get(i)]!=1)
{
depth++;
size += dfs(map,ans,child.get(i),visited);
depth--;
}
}
}
ans[currN] = depth - size;
return size + 1;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
f57985f33d004dede87cb59973a6b8eb
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
public class Main
{
static int child[] ; static ArrayList<ArrayList<Integer>> grph;
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
solve();
}
}, "1", 1 << 26).start();
}
static void solve () {
FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out);
int n =fr.nextInt() ,K =fr.nextInt() ,i ,j ,k ,l ,m ,lvl[] =new int[n] ,val[] =new int[n] ; long sm =0l ;
grph =new ArrayList<>() ; child =new int[n] ;
for (i =0 ; i<n ; ++i) {
grph.add(new ArrayList<>()) ; lvl[i] =-1 ;
}
for (i =1 ; i<n ; ++i) {
j =fr.nextInt()-1 ; k =fr.nextInt()-1 ;
grph.get(j).add(k) ; grph.get(k).add(j) ;
}
dfs(0,-1); Queue<Integer> q =new LinkedList<>() ; q.add(0) ; lvl[0] =val[0] =0 ;
while (!q.isEmpty()) {
i =q.poll() ;
for (j =0 ; j<grph.get(i).size() ; ++j) {
k =grph.get(i).get(j) ; if (lvl[k]!=-1) continue;
lvl[k] =val[k] =lvl[i]+1 ; q.add(k) ;
}
}
for (i =0 ; i<n ; ++i) val[i] =lvl[i] - child[i] ; sort (val,0,n-1) ; i =n-1 ;
while (K>0) {
sm += (long)val[i] ; --i ; --K;
}
op.println(sm) ; op.flush(); op.close();
}
static void dfs (int nd , int p) {
int i ,j ; child[nd] =0 ;
for (i =0 ; i<grph.get(nd).size() ; ++i) {
j =grph.get(nd).get(i) ; if (j==p) continue;
dfs (j,nd) ; child[nd] += (child[j]+1) ;
}
}
public static void sort(int[] arr , int l , int u) {
int m ;
if(l < u){
m =(l + u)/2 ;
sort(arr , l , m); sort(arr , m + 1 , u);
merge(arr , l , m , u);
}
}
public static void merge(int[] arr , int l , int m , int u) {
int[] low = new int[m - l + 1] ;
int[] upr = new int[u - m] ;
int i ,j =0 ,k =0 ;
for(i =l;i<=m;i++)
low[i - l] =arr[i] ;
for(i =m + 1;i<=u;i++)
upr[i - m - 1] =arr[i] ;
i =l;
while((j < low.length) && (k < upr.length))
{
if(low[j] < upr[k])
arr[i++] =low[j++] ;
else
arr[i++] =upr[k++] ;
}
while(j < low.length)
arr[i++] =low[j++] ;
while(k < upr.length)
arr[i++] =upr[k++] ;
}
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();
}
String nextLine() {
String str ="";
try
{
str =br.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next()) ;
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
202fffb8072e545fd8e155eb43903390
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class spoj {
InputStream is;
static PrintWriter out;
static Integer level[];
static int down[];
static int dfs2(ArrayList<Integer> l[],int cur,int par,int root)
{
if(l[cur].size()==1 && cur!=root)
{
return 0;
}
for(int i=0;i<l[cur].size();i++)
{
int v=l[cur].get(i);
if(v!=par)
{
down[cur]+=(1+dfs2(l,v,cur,0));
}
}
return down[cur];
}
static void dfs(ArrayList<Integer> l[],int cur,int par,int sm,int n,int vis[])
{
if(vis[cur]==-1)
level[cur]=sm;
vis[cur]=1;
for(int i=0;i<l[cur].size();i++)
{
int v=l[cur].get(i);
if(v!=par)
{
dfs(l,v,cur,sm+1,n+1,vis);
}
}
}
void solve()
{
int n=ni(),k=ni();
level=new Integer[n];
down=new int[n];
ArrayList<Integer> l[]=new ArrayList[n];
for(int i=0;i<n;i++)
l[i]=new ArrayList<Integer>();
for(int i=0;i<n-1;i++)
{
int x=ni()-1,y=ni()-1;
l[x].add(y);
l[y].add(x);
}
int vis[]=new int[n];
Arrays.fill(vis,-1);
dfs(l,0,-1,0,0,vis);
dfs2(l,0,-1,0);
//pa(down);
for(int i=0;i<n;i++)
level[i]=level[i]-down[i];
Arrays.sort(level);
long sm=0;
int pt=n-1;
while(k-->0)
{
sm+=level[pt--];
}
out.println(sm);
}
//---------- I/O Template ----------
public static void main(String[] args) { new spoj().run(); }
void run() {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if(ptr >= len) { ptr = 0;
try { len = is.read(input); }
catch(IOException e) { throw new InputMismatchException(); }
if(len <= 0) { return -1; }
} return input[ptr++];
}
boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
int skip() {
int b = readByte();
while(b != -1 && isSpaceChar(b)) { b = readByte(); }
return b;
}
char nc() { return (char)skip(); }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
if(b == -1) { return -1; } //no input
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
long nl() {
long n = 0L; int b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
double nd() { return Double.parseDouble(ns()); }
float nf() { return Float.parseFloat(ns()); }
int[] na(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) { a[i] = ni(); }
return a;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for(i = 0; i < n; i++) {
if(isSpaceChar(b)) { break; }
c[i] = (char)b; b = readByte();
} return i == n ? c : Arrays.copyOf(c,i);
}
static void pa(int a[])
{
for(int i=0;i<a.length;i++)
out.print(a[i]+" ");
out.println();
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
446b6e9b9157974162eec623d15adfd1
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<27).start();
}
static int dfs(HashMap<Integer,ArrayList<Integer>>a,int x,boolean [] visited, int cnt, int arr[],int s[])
{
int helo=0;
if(visited[x]==false)
{
visited[x]=true;
cnt=cnt+1;
arr[x]=cnt;
helo++;
for(int i=0;i<a.get(x).size();i++){
//System.out.println(x+" wherex ");
helo=helo+dfs(a,a.get(x).get(i),visited,cnt,arr,s);
}
s[x]=helo;
}
return helo;
}
public void run(){
InputReader sc=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int k=sc.nextInt();
HashMap<Integer,ArrayList<Integer>> map=new HashMap<>();
for(int i=0;i<n-1;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
if(map.containsKey(x))
{
map.get(x).add(y);
map.put(x,map.get(x));
}
else
{
ArrayList<Integer> w=new ArrayList<Integer>();
w.add(y);
map.put(x,w);
}
if(map.containsKey(y))
{
map.get(y).add(x);
map.put(y,map.get(y));
}
else
{
ArrayList<Integer> w=new ArrayList<Integer>();
w.add(x);
map.put(y,w);
}
}
int child[]=new int[n+1];
boolean visited[]=new boolean[n+1];
int distance[]=new int[n+1];
dfs(map,1,visited,0,distance,child);
/*for(int i=0;i<n+1;i++)
System.out.print(distance[i]+" dis ");
System.out.println();
for(int i=0;i<n+1;i++)
System.out.print(child[i]+" chil ");
System.out.println();*/
Integer g[]=new Integer[n+1];
for(int i=1;i<n+1;i++)
g[i]=distance[i]-child[i];
Arrays.sort(g,1,n+1,Collections.reverseOrder());
/*for(int i=1;i<n+1;i++)
System.out.print(g[i]+" diff ");*/
long ans=0;
for(int i=1;i<=k;i++)
ans=ans+g[i];
System.out.println(ans);
out.flush();
out.close();
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
5200801545cd13b5e766b48a640aecb5
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
HashMap<Integer,ArrayList<Integer>> map=new HashMap<>();
for(int i=0;i<n-1;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
if(map.containsKey(x))
{
map.get(x).add(y);
map.put(x,map.get(x));
}
else
{
ArrayList<Integer> w=new ArrayList<Integer>();
w.add(y);
map.put(x,w);
}
if(map.containsKey(y))
{
map.get(y).add(x);
map.put(y,map.get(y));
}
else
{
ArrayList<Integer> w=new ArrayList<Integer>();
w.add(x);
map.put(y,w);
}
}
int child[]=new int[n+1];
boolean visited[]=new boolean[n+1];
int distance[]=new int[n+1];
dfs(map,1,visited,0,distance,child);
/*for(int i=0;i<n+1;i++)
System.out.print(distance[i]+" dis ");
System.out.println();
for(int i=0;i<n+1;i++)
System.out.print(child[i]+" chil ");
System.out.println();*/
Integer g[]=new Integer[n+1];
for(int i=1;i<n+1;i++)
g[i]=distance[i]-child[i];
Arrays.sort(g,1,n+1,Collections.reverseOrder());
/*for(int i=1;i<n+1;i++)
System.out.print(g[i]+" diff ");*/
long ans=0;
for(int i=1;i<=k;i++)
ans=ans+g[i];
System.out.println(ans);
}
//static int helo=0;
static int dfs(HashMap<Integer,ArrayList<Integer>>a,int x,boolean [] visited, int cnt, int arr[],int s[])
{
int helo=0;
if(visited[x]==false)
{
visited[x]=true;
cnt=cnt+1;
arr[x]=cnt;
helo++;
for(int i=0;i<a.get(x).size();i++){
//System.out.println(x+" wherex ");
helo=helo+dfs(a,a.get(x).get(i),visited,cnt,arr,s);
}
s[x]=helo;
}
return helo;
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
d2a8239378e298760325efccacab3d83
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int k = input.nextInt();
Map<Integer, List<Integer>> tree = new HashMap<>();
for (int i = 0; i < n - 1; i++) {
int a = input.nextInt() - 1;
int b = input.nextInt() - 1;
tree.computeIfAbsent(a, key -> new ArrayList<>()).add(b);
tree.computeIfAbsent(b, key -> new ArrayList<>()).add(a);
}
HashMap<Integer, Integer> subTreeSize = new HashMap<>();
HashMap<Integer, Integer> depthMap = new HashMap<>();
populateMap(0, -1, 0, tree, subTreeSize, depthMap);
TreeMap<Integer, List<Integer>> orderBySize = new TreeMap<>();
for (Map.Entry<Integer, Integer> entry : subTreeSize.entrySet()) {
orderBySize.computeIfAbsent(entry.getValue() - depthMap.get(entry.getKey()), key -> new ArrayList<>()).add(entry.getKey());
}
Set<Integer> industries = new HashSet<>();
for (Map.Entry<Integer, List<Integer>> entry : orderBySize.entrySet()) {
for (Integer v : entry.getValue()) {
industries.add(v);
k--;
if (k == 0) {
break;
}
}
if (k == 0) {
break;
}
}
AtomicLong ans = new AtomicLong(0);
rec(0, -1, 0, tree, industries, ans);
System.out.println(ans.get());
}
private static void rec(int cur, int parent, int score, Map<Integer, List<Integer>> tree, Set<Integer> industries,
AtomicLong ans) {
int delta = 1;
if (industries.contains(cur)) {
delta = 0;
ans.addAndGet(score);
}
for (Integer child : tree.get(cur)) {
if (child != parent) {
rec(child, cur, score + delta, tree, industries, ans);
}
}
}
private static int populateMap(int cur,
int parent,
int depth, Map<Integer, List<Integer>> tree,
HashMap<Integer, Integer> subTreeSize,
HashMap<Integer, Integer> depthMap) {
depthMap.put(cur, depth);
int count = 0;
for (int child : tree.get(cur)) {
if (child != parent) {
count += populateMap(child, cur, depth + 1, tree, subTreeSize, depthMap);
}
}
subTreeSize.put(cur, count);
return count + 1;
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
03777ea688b0520f68916f68823c1554
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ProblemC {
public static void ez(int v) {
used[v] = true;
for (int i = 0; i < arr.get(v).size(); i++) {
int v1 = arr.get(v).get(i);
if (used[v1] == false) {
len[v1] = len[v] + 1;
ban[v]++;
ez(v1);
ban[v] += ban[v1];
}
}
}
static int n;
static boolean used[];
static int len[];
static int ban[];
static ArrayList<ArrayList<Integer>> arr;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
arr=new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < n; i++) {
arr.add(new ArrayList<Integer>());
}
used = new boolean[n];
len = new int[n];
ban = new int[n];
int k = sc.nextInt();
for (int i = 0; i < n - 1; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
arr.get(a).add(b);
arr.get(b).add(a);
}
ez(0);
int ans[] = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = len[i] - ban[i];
// System.out.println(ans[i]);
}
Arrays.sort(ans);
long gg = 0;
int cnt = n - 1;
for (int i = 0; i < k; i++) {
gg += ans[cnt];
cnt--;
}
System.out.println(gg);
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
f9f4b98ca524bed64709a30159066ff3
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
/**
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class LinovaKingdom {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
int K = sc.nextInt();
adjList = new ArrayList[N];
Arrays.setAll(adjList, x -> new ArrayList<>());
for (int i = 0; i < N - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjList[u].add(v);
adjList[v].add(u);
}
nodes = new ArrayList<>();
height = new long[N];
delta = new long[N];
sub = new int[N];
parent = new int[N];
dfs(0, -1, 0);
Collections.sort(nodes);
ArrayList<Node> used = new ArrayList<>();
for (int i = 0; i < K; i++) {
Node node = nodes.get(i);
used.add(node);
for (int adj : adjList[node.i]) {
if (adj != parent[node.i]) {
delta[adj]++;
}
}
}
/*
11 7
1 2
1 3
2 4
2 5
3 6
6 11
4 7
4 8
5 9
5 10
*/
apply(0, -1);
// System.out.println(Arrays.toString(parent));
// System.out.println(Arrays.toString(delta));
// System.out.println(nodes);
// System.out.println(used);
long ans = 0;
for (Node node : used) {
if (height[node.i] < delta[node.i]) {
System.exit(0);
}
ans += height[node.i] - delta[node.i];
}
out.println(ans);
out.close();
}
static ArrayList<Integer>[] adjList;
static long[] height;
static int[] sub, parent;
static long[] delta;
static ArrayList<Node> nodes;
static int dfs(int node, int par, int h) {
height[node] = h;
parent[node] = par;
sub[node] = 1;
nodes.add(new Node(node, h));
for (int adj : adjList[node]) {
if (adj != par) {
sub[node] += dfs(adj, node, h + 1);
}
}
return sub[node];
}
static void apply(int node, int par) {
for (int adj : adjList[node]) {
if (adj != par) {
delta[adj] += delta[node];
apply(adj, node);
}
}
}
static class Node implements Comparable<Node> {
int i, h;
public Node(int ii, int hh) {
i = ii;
h = hh;
}
public String toString() {
return "(" + i + ": " + h + ")";
}
public int compareTo(Node n2) {
// decr h, incr sub size
/**
* Actually, sometimes we might not want to place
* an industry at the deepest, because it'll contract
* a cost to all the nodes below it. So, compare based
* on the subtree size cost that it may incur.
* We want sort by bigger values
*/
int myValue = (h - (sub[i] - 1));
int hisValue = (n2.h - (sub[n2.i] - 1));
return hisValue - myValue;
}
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
0ba3f8e93c093b441bae82634897da21
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C {
static final boolean stdin = true;
static final String filename = "";
static FastScanner br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
if (stdin) {
br = new FastScanner();
pw = new PrintWriter(new OutputStreamWriter(System.out));
} else {
br = new FastScanner(filename + ".in");
pw = new PrintWriter(new FileWriter(filename + ".out"));
}
Solver solver = new Solver();
solver.solve(br, pw);
pw.close();
}
static class Solver {
static long mod = (long) (1e9);
static ArrayList<Integer>[] adj;
static int[] children;
static int[] depth;
static int[] cnt;
static boolean[] indus;
public void solve(FastScanner br, PrintWriter pw) throws IOException {
int n = br.ni();
int k = br.ni(); // industry
adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int a = br.ni() - 1;
int b = br.ni() - 1;
adj[a].add(b);
adj[b].add(a);
}
children = new int[n];
depth = new int[n];
dfs(0, -1, 1);
Point[] c = new Point[n];
for (int i = 0; i < n; i++) {
c[i] = new Point(depth[i] - children[i] - 1, i);
}
Arrays.parallelSort(c);
indus = new boolean[n];
for (int i = 0; i < k; i++) {
indus[c[i].b] = true;
}
cnt = new int[n];
dfs2(0, -1, 0);
long x = 0;
for (int i : cnt) {
x += i;
}
pw.println(x);
}
static void dfs2(int i, int p, int t) {
// System.out.println(i + " " + t);
if (!indus[i])
t++;
else {
cnt[i] = t;
//System.out.println(t);
}
for (int j : adj[i]) {
if (j == p)
continue;
dfs2(j, i, t);
}
}
static int dfs(int i, int p, int d) {
int cnt = 1;
for (int j : adj[i]) {
if (j == p)
continue;
cnt += dfs(j, i, d + 1);
}
children[i] = cnt;
depth[i] = d;
return cnt;
}
static long gcd(long a, long b) {
if (a > b)
return gcd(b, a);
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
static long pow(long a, long b) {
if (b == 0)
return 1L;
long val = pow(a, b / 2);
if (b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
}
static class Point implements Comparable<Point> {
int a;
int b;
Point(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Point o) {
if(this.a==o.a)return this.b-o.b;
return -this.a + o.a;
}
public boolean equals(Object obj) {
if (obj instanceof Point) {
Point other = (Point) obj;
return a == other.a && b == other.b;
}
return false;
}
public int hashCode() {
return 65536 * a + b + 4733 * 0;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
ArrayList<Integer>[] ng(int n, int e) {
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < e; i++) {
int a = ni() - 1;
int b = ni() - 1;
adj[a].add(b);
adj[b].add(a);
}
return adj;
}
Integer[] nIa(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
int[] nia(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
Long[] nLa(int n) {
Long[] arr = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = nl();
}
return arr;
}
long[] nla(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nl();
}
return arr;
}
String[] nsa(int n) {
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = nt();
}
return arr;
}
String nt() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(nt());
}
long nl() {
return Long.parseLong(nt());
}
double nd() {
return Double.parseDouble(nt());
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
fe6d7f1268fa83c85901b42d26adabf3
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.util.*;
public class C635_PC {
public static ArrayList<Integer>[] adj;
public static int[] visit;
public static int[] size;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
adj = new ArrayList[n+1];
for(int i=0;i<=n;i++)
adj[i] = new ArrayList<Integer>();
for(int i = 0;i<n-1;i++)
{
int u = in.nextInt();
int v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
visit = new int[n+1];
size = new int[n+1];
Arrays.fill(visit, -1);
dfs(1,0);
//System.out.println(Arrays.toString(visit));
//System.out.println(Arrays.toString(size));
pair[] p = new pair[n+1];
p[0] = new pair(5000000,0);
for(int i=1;i<=n;i++)
{
p[i] = new pair(visit[i],size[i]-1);
}
Arrays.sort(p);
long ans = 0;
for(int i =0;i<n-k;i++)
{
ans +=p[i].y-p[i].x;
}
//System.out.println(Arrays.toString(p));
System.out.println(ans);
}
static class pair implements Comparable<pair>
{
int x,y;
public pair(int x,int y)
{
this.x = x;
this.y = y;
}
public int compareTo(pair that)
{
return (that.y-that.x)-(this.y-this.x);
}
public String toString()
{
return "("+x+", " +y+")";
}
}
public static int dfs(int i, int depth)
{
visit[i] = depth;
int sum =1;
for(int v:adj[i])
{
if(visit[v]==-1)
{
sum+=dfs(v,depth+1);
}
}
return size[i]=sum;
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
55393d40e13224ae634c850dda69c2ac
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
//package codeforces._635;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class _635_C {
public static void main (String[] args) throws Exception {
String s = "7 4\n" +
"1 2\n" +
"1 3\n" +
"1 4\n" +
"3 5\n" +
"3 6\n" +
"4 7";
// String s = "9 6\n" +
// "1 2\n" +
// "1 3\n" +
// "1 4\n" +
// "3 5\n" +
// "3 6\n" +
// "4 7\n" +
// "6 8\n" +
// "6 9\n"
;
// String s = "4 1\n" +
// "1 2\n" +
// "1 3\n" +
// "2 4";
// String s = "8 5\n" +
// "7 5\n" +
// "1 7\n" +
// "6 1\n" +
// "3 7\n" +
// "8 3\n" +
// "2 1\n" +
// "4 5";
// 38
// String s = "20 7\n" +
// "9 7\n" +
// "3 7\n" +
// "15 9\n" +
// "1 3\n" +
// "11 9\n" +
// "18 7\n" +
// "17 18\n" +
// "20 1\n" +
// "4 11\n" +
// "2 11\n" +
// "12 18\n" +
// "8 18\n" +
// "13 2\n" +
// "19 2\n" +
// "10 9\n" +
// "6 13\n" +
// "5 8\n" +
// "14 1\n" +
// "16 13";
// StringBuffer sb = new StringBuffer("200000 66666\n");
// Random r = new Random();
// for (int i=2; i<=200000; ++i) {
//// int C = r.nextInt(1000000000);
//// C = Math.abs(C);
// sb.append(i + " " + 1 + "\n");
//// System.out.print(C + " ");
// }
// String s = sb.toString();
long time = System.currentTimeMillis();
// br = new BufferedReader(new StringReader(s));
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
rl(); int n = nin(); int k=nin();
Town[] towns = new Town[n];
for (int i=0; i<n; ++i) {
towns[i] = new Town();
towns[i].index = i+1;
}
HashMap<Integer, ArrayList<Integer>> paths = new HashMap<>();
for (int i=0; i<n-1; ++i) {
rl(); int u = nin(); int v = nin();
if (paths.get(u-1) == null) paths.put(u-1, new ArrayList<>());
paths.get(u-1).add(v-1);
if (paths.get(v-1) == null) paths.put(v-1, new ArrayList<>());
paths.get(v-1).add(u-1);
}
// System.out.println("time 1 " + (System.currentTimeMillis()-time));
Stack<Integer> st = new Stack<>();
st.add(0);
while (!st.isEmpty()) {
Integer ind = st.pop();
if (ind !=null && paths.get(ind)!=null) {
for (Integer i : paths.get(ind)) {
if (towns[i].chidren.size()==0) {
towns[ind].chidren.add(towns[i]);
towns[i].parent = towns[ind];
st.push(i);
}
}
}
}
// System.out.println("time 2 " + (System.currentTimeMillis()-time));
Town parent = towns[0];
Stack<Town> stack = new Stack<>();
stack.push(parent);
while (!stack.empty()) {
Town t = stack.peek();
boolean toPop = true;
for (Town _t : t.chidren) {
if (!_t.visited) {
_t.dep = t.dep+1;
stack.push(_t);
toPop = false;
}
}
if (toPop) {
if (t.parent != null) {
t.parent.siz += t.siz;
t.visited = true;
}
stack.pop();
}
}
// System.out.println("time 3 " + (System.currentTimeMillis()-time));
Comparator<Town> comparator = new Comparator<Town>() {
public int compare(Town o1, Town o2) {
return Integer.compare((o2.siz-o2.dep), (o1.siz-o1.dep));
}
};
// System.out.println("time 4 " + (System.currentTimeMillis()-time));
long result = 0;
Arrays.sort(towns, comparator);
for (int i=0; i<n-k; ++i) {
result += (towns[i].siz-towns[i].dep);
}
// System.out.println("time 5 " + (System.currentTimeMillis()-time));
bw.write(Long.toString(result));
bw.newLine();
bw.flush();
}
static class Town {
int index;
Town parent;
ArrayList<Town> chidren = new ArrayList<Town>();
int dep=1;
int siz=1;
boolean visited = false;
}
static BufferedReader br;
static BufferedWriter bw;
static StringTokenizer st;
static void rl() throws Exception{
st = new StringTokenizer(br.readLine());
}
static long nlo(){
return Long.parseLong(st.nextToken());
}
static int nin(){
return Integer.parseInt(st.nextToken());
}
/*private static void te(){
}*/
static double ndo(){
return Double.parseDouble(st.nextToken());
}
static char[] nca(){
return st.nextToken().toCharArray();
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
3ab132ab4068492182d5c977aad1e46e
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CodingLegacy {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Palindrome solver = new Palindrome();
int t = 1;
// t = in.nextInt();
for (int i = 0; i < t; i++) {
solver.solve(i + 1, in, out);
}
out.close();
}
static class Palindrome {
static long mod = 1000000007;
static long maxX = (long) 1e18;
static long mod2 = 998244353;
ArrayList<Integer>[] graph;
int[] level;int n;
boolean[] visited;
int[] leaf,total;
void solve(int testNumber, ScanReader in, PrintWriter out) {
n = in.nextInt();int k = in.nextInt();
graph = new ArrayList[n+1];
level = new int[n+1];
leaf = new int[n+1];
visited = new boolean[n+1];
total = new int[n+1];
for(int i = 0;i<=n;i++) {
graph[i] = new ArrayList<>();
}
for(int i = 0;i+1<n;i++) {
int u = in.nextInt(),v = in.nextInt();
--u;--v;
graph[u].add(v);
graph[v].add(u);
}
dfs(0,1);
// out.println(Arrays.toString(leaf));
// out.println(Arrays.toString(total));
Long[] gain = new Long[n];
for(int i = 0;i<n;i++) {
gain[i] = (long) (leaf[i] - total[i] );
}
Arrays.sort(gain, new
Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
return Long.compare(o2,o1);
}
});
// out.println(Arrays.toString(gain));
long ans = 0;
for(int i = 0;i<k;i++) {
ans += gain[i];
}
out.println(ans);
}
private void dfs(int v,int level) {
visited[v] = true;
leaf[v] = level;
total[v] = 1;
for (int aa : graph[v]) {
if(!visited[aa]){
dfs(aa,level + 1);
total[v] += total[aa];
}
}
}
}
static class ScanReader {
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 ScanReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
63bc4d84b94d287297da51a5a9e4e861
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.awt.*;
public class C
{
BufferedReader in;
PrintWriter ob;
StringTokenizer st;
public ArrayList<ArrayList<Integer>> gr;
public PriorityQueue<Integer> pq;
public boolean vis[];
public int level[];
public int subtree[];
public static void main(String[] args) throws IOException {
new C().run();
}
void run() throws IOException {
in=new BufferedReader(new InputStreamReader(System.in));
ob=new PrintWriter(System.out);
solve();
ob.flush();
}
void solve() throws IOException {
int n = ni();
int k = ni();
gr = new ArrayList<>();
pq = new PriorityQueue<>(new Comparator<Integer>(){
public int compare( Integer a , Integer b ) {
if( a == b )
return -1;
else
return Integer.compare( b , a );
}
});
vis = new boolean[n+1];
level = new int[n+1];
subtree = new int[n+1];
for(int i=0 ; i<=n ; i++)
gr.add(new ArrayList<Integer>());
for (int i=1; i<=n-1 ;i++ ) {
int u = ni();
int v = ni();
gr.get(u).add(v);
gr.get(v).add(u);
}
dfs( 1 , -1 , 0 );
long ans = 0;
for(int need = 1; need <= k ; need++ ) {
ans += pq.poll();
}
ob.println(ans);
}
void dfs( int u , int parent , int h ) {
level[u] = h;
vis[u] = true;
for(int v : gr.get(u)) {
if( v != parent ) {
dfs( v , u , h+1 );
subtree[u]+=subtree[v]+1;
}
}
pq.add( level[u] - subtree[u] );
}
String ns() throws IOException {
return nextToken();
}
long nl() throws IOException {
return Long.parseLong(nextToken());
}
int ni() throws IOException {
return Integer.parseInt(nextToken());
}
double nd() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
if(st==null || !st.hasMoreTokens())
st=new StringTokenizer(in.readLine());
return st.nextToken();
}
int[] nia(int start,int b) throws IOException {
int a[]=new int[b];
for(int i=start;i<b;i++)
a[i]=ni();
return a;
}
long[] nla(int start,int n) throws IOException {
long a[]=new long[n];
for (int i=start; i<n ;i++ ) {
a[i]=nl();
}
return a;
}
class Point {
int h;
boolean leaf;
int index;
Point( int h , boolean leaf , int index ) {
this.h = h;
this.leaf = leaf;
this.index = index;
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
72161c9ef4801ea085ef9a0e38b55279
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.awt.*;
public class C
{
BufferedReader in;
PrintWriter ob;
StringTokenizer st;
public ArrayList<ArrayList<Integer>> gr;
public PriorityQueue<Integer> pq;
public boolean vis[];
public int level[];
public int subtree[];
public static void main(String[] args) throws IOException {
new C().run();
}
void run() throws IOException {
in=new BufferedReader(new InputStreamReader(System.in));
ob=new PrintWriter(System.out);
solve();
ob.flush();
}
void solve() throws IOException {
int n = ni();
int k = ni();
gr = new ArrayList<>();
pq = new PriorityQueue<>(new Comparator<Integer>(){
public int compare( Integer a , Integer b ) {
if( a == b )
return -1;
else
return Integer.compare( b , a );
}
});
vis = new boolean[n+1];
level = new int[n+1];
subtree = new int[n+1];
for(int i=0 ; i<=n ; i++)
gr.add(new ArrayList<Integer>());
for (int i=1; i<=n-1 ;i++ ) {
int u = ni();
int v = ni();
gr.get(u).add(v);
gr.get(v).add(u);
}
dfs( 1 , -1 , 0 );
long ans = 0;
for(int need = 1; need <= k ; need++ ) {
ans += pq.poll();
}
ob.println(ans);
}
void dfs( int u , int parent , int h ) {
level[u] = h;
vis[u] = true;
boolean isLeaf = true;
for(int v : gr.get(u)) {
if( v != parent ) {
dfs( v , u , h+1 );
isLeaf = false;
subtree[u]+=subtree[v]+1;
}
}
pq.add( level[u] - subtree[u] );
}
String ns() throws IOException {
return nextToken();
}
long nl() throws IOException {
return Long.parseLong(nextToken());
}
int ni() throws IOException {
return Integer.parseInt(nextToken());
}
double nd() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
if(st==null || !st.hasMoreTokens())
st=new StringTokenizer(in.readLine());
return st.nextToken();
}
int[] nia(int start,int b) throws IOException {
int a[]=new int[b];
for(int i=start;i<b;i++)
a[i]=ni();
return a;
}
long[] nla(int start,int n) throws IOException {
long a[]=new long[n];
for (int i=start; i<n ;i++ ) {
a[i]=nl();
}
return a;
}
class Point {
int h;
boolean leaf;
int index;
Point( int h , boolean leaf , int index ) {
this.h = h;
this.leaf = leaf;
this.index = index;
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
b49a2ad5f0e322b4961c1fb55d49903c
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
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)
{
class Graph
{
int V; // No. of vertices
LinkedList<Integer> adj[]; //Adjacency Lists
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v,int w)
{
adj[v].add(w);
adj[w].add(v);
}
void dfs_happiness(long[] distances,long[] subtreeSizes)
{
boolean[] visited = new boolean[V];
distances[0]=0;
DFS(0,visited,distances,subtreeSizes);
}
private long DFS(int current, boolean[] visited,
long[] distances, long[] subtreeSizes) {
visited[current] = true;
for(int nxt:adj[current])
{
if(!visited[nxt])
{
distances[nxt]=distances[current]+1;
subtreeSizes[current]+=DFS(nxt,visited,distances,subtreeSizes);
}
}
return subtreeSizes[current]+1;
}
}
FastReader s = new FastReader();
int n = s.nextInt(), k = s.nextInt();
Graph cities = new Graph(n);
for (int i = 0; i < n - 1; i++) {
int u = s.nextInt();
int v = s.nextInt();
cities.addEdge(u-1,v-1);
}
long[] distances = new long[n];
long[] subtreeSizes = new long[n];
cities.dfs_happiness(distances,subtreeSizes);
long[] total = new long[n];
for (int i = 0; i < n; i++)
total[i] = distances[i] - subtreeSizes[i];
Arrays.sort(total);
long happiness = 0;
int index = n-1;
while(k-->0) happiness+=total[index--];
System.out.println(happiness);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int[] nextIntArr() {
String[] str = nextLine().split(" ");
int[] arr = new int[str.length];
try
{
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.parseInt(str[i]);
}
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
return arr;
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
320415f28dde2743e2f662e1e16f9515
|
train_001.jsonl
|
1586961300
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.Β There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
256 megabytes
|
/**
* The author of the following code is - Dewansh Nigam
* Username - dewanshnigam
* Unstoppable Now.
*/
// The author of this Code is -> Dewansh Nigam
// Username -> dewanshnigam
import java.util.*;
import java.io.*;
public class CF1
{
// cycle in a directed graph dfs.
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
public static void main(String args[])throws IOException
{
int t=1;
StringBuilder sb=new StringBuilder();
while(t-->0)
{
int n=in.readInt(); // number of vertices
int k=in.readInt();
Graph graph = new Graph(n,n-1);
for (int i = 0; i < n-1; i++) {
int u = in.readInt();
int v = in.readInt();
--u;
--v;
graph.addEdge(u, v);
}
long sum = graph.solve(k);
sb.append(sum+"\n");
}
out.printLine(sb);
out.close();
}
static class Graph // This time directed
{
int n;
int m;
Node nd[];
public Graph(int n,int m)
{
this.n=n;
this.m=m;
nd=new Node[n];
for(int i=0;i<n;i++){
nd[i] = new Node(i);
}
}
public void addEdge(int u,int v)
{
nd[u].edges.add(v);
nd[v].edges.add(u);
}
public long solve(int k) {
// k will always be less than n.
dfs(0,-1);
// this will calculate the depths and subtree for each node.
Arrays.sort(nd, new Sort());
/*
for(Node s:nd) {
System.out.println("Index : "+s.index + " Depth : "+ s.depth +" Subtree : "+s.subtree+" Diff : "+(s.depth - s.subtree));
}
*/
long sum=0L;
for(int i=0;i<k;i++) {
sum += ( nd[i].depth - nd[i].subtree );
}
return sum;
}
public int dfs(int index, int parent) {
if(parent == -1)
nd[index].depth = 0;
nd[index].subtree = 0;
for(int adj : nd[index].edges) {
if(adj == parent)
continue;
nd[adj].depth = nd[index].depth + 1;
nd[index].subtree++;
nd[index].subtree += dfs(adj,index);
}
return nd[index].subtree;
}
}
static class Node
{
int index;
int depth;
int subtree;
ArrayList<Integer> edges;
public Node(int index){
this.index = index;
edges = new ArrayList<Integer>();
}
}
static class Sort implements Comparator<Node> {
public int compare(Node a, Node b) {
int v1 = a.depth - a.subtree;
int v2 = b.depth - b.subtree;
return v2 - v1;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static 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();
}
}
}
|
Java
|
["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"]
|
2 seconds
|
["7", "2", "9"]
|
NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.
|
Java 8
|
standard input
|
[
"dp",
"greedy",
"sortings",
"dfs and similar",
"trees"
] |
47129977694cb371c7647cfd0db63d29
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$) Β β the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.
| 1,600
|
Print the only line containing a single integer Β β the maximum possible sum of happinesses of all envoys.
|
standard output
| |
PASSED
|
4e4670f390db269558f9f7fec5d66145
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class myclass{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int ct=0;
while(n>0){
String s=sc.next();
if(s.equals("Cube")){
ct+=6;
}
else if(s.equals("Tetrahedron")){
ct+=4;
}
else if(s.equals("Dodecahedron")){
ct+=12;
}
else if(s.equals("Octahedron")){
ct+=8;
}
else{
ct+=20;
}
n--;
}
System.out.println(ct);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
972a6f9429bd456028a35aaa08ba0d93
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
// Problem number: 785A
import java.util.Scanner;
public class Anton {
static int getFaceCount() {
Scanner in = new Scanner(System.in);
int total = in.nextInt();
in.nextLine();
int facesCount = 0;
for(int i = 0; i < total; i++) {
if(in.hasNextLine()) {
String polyhedron = in.nextLine();
switch (polyhedron) {
case "Tetrahedron":
facesCount += 4;
break;
case "Cube":
facesCount += 6;
break;
case "Octahedron":
facesCount += 8;
break;
case "Dodecahedron":
facesCount += 12;
break;
case "Icosahedron":
facesCount += 20;
break;
default:
break;
}
}
}
return facesCount;
}
public static void main(String [] args) {
int result = getFaceCount();
System.out.println(result);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
71a595d0a3ef9b447630e5e46251cbfe
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc =new Scanner (System.in);
int n=sc.nextInt();
String m;
int sum=0;
for(int i=0;i<=n;i++){
m=sc.nextLine();
switch(m){
case"Tetrahedron":sum+=4;break;
case"Cube":sum+=6;break;
case"Octahedron":sum+=8;break;
case"Dodecahedron":sum+=12;break;
case"Icosahedron":sum+=20;break;
}
}
System.out.println(sum);
}}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
41e38c1daa9eafe388947ae888739d60
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Polyhedrons {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
int n = sc.nextInt();
for(int i=0; i<n; i++){
String in = sc.next();
if(in.equals("Tetrahedron")){
sum = sum + 4;
} else if(in.equals("Cube")){
sum = sum + 6;
} else if(in.equals("Octahedron")) {
sum = sum + 8;
} else if(in.equals("Dodecahedron")) {
sum = sum + 12;
} else if(in.equals("Icosahedron")) {
sum = sum + 20;
}
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
d71b7c165a4a41091788e3f88eaab353
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Polyhedrons {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
int n = sc.nextInt();
for(int i=0; i<=n; i++){
String in = sc.nextLine();
if(in.equals("Tetrahedron")){
sum = sum + 4;
} else if(in.equals("Cube")){
sum = sum + 6;
} else if(in.equals("Octahedron")) {
sum = sum + 8;
} else if(in.equals("Dodecahedron")) {
sum = sum + 12;
} else if(in.equals("Icosahedron")) {
sum = sum + 20;
}
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
aba29959d5e95a200f75dca75dbe9222
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class Anton_and_Polyhedrons {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n;
String vec[] = new String[21];
vec[4] = "Tetrahedron";
vec[6] = "Cube";
vec[8] = "Octahedron";
vec[12] = "Dodecahedron";
vec[20] = "Icosahedron";
String s;
int x;
while(sc.hasNext()) {
n = sc.nextInt();
sc.nextLine();
x = 0;
for(int i = 0; i<n; i++) {
s = sc.nextLine();
for(int j = 0; j<vec.length; j++) {
if(s.equals(vec[j])) {
x = x+j;
}
}
}
System.out.println(x);
}
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
0a745994f5277f91ce1b5b041fe92f1f
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class Anton_and_Polyhedrons {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n;
//String vec[] = new String[21];
/*vec[4] = "Tetrahedron";
vec[6] = "Cube";
vec[8] = "Octahedron";
vec[12] = "Dodecahedron";
vec[20] = "Icosahedron";*/
String a = "Tetrahedron";
String b= "Cube";
String c= "Octahedron";
String d= "Dodecahedron";
String e = "Icosahedron";
String s;
int x;
while(sc.hasNext()) {
n = sc.nextInt();
sc.nextLine();
x = 0;
for(int i =0;i<n;i++) {
s = sc.nextLine();
if(s.equals(a)) {
x = x+4;
}else if(s.equals(b)) {
x = x+6;
} else if(s.equals(c)) {
x = x+8;
} else if(s.equals(d)) {
x = x+12;
} else if(s.equals(e)) {
x = x+20;
}
}
/*for(int i = 0; i<n; i++) {
s = sc.nextLine();
for(int j = 0; j<vec.length; j++) {
if(s.equals(vec[j])) {
x = x+j;
}
}
}*/
System.out.println(x);
}
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
b85c63041dfe816f53c51288d9e9b9bb
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class AntonandPolyhedrons {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int sum = 0;
for (int i = 0; i <= n; i++) {
String polyhedron = scanner.nextLine();
if (polyhedron.equals("Tetrahedron")) sum += 4;
else if (polyhedron.equals("Cube")) sum += 6;
else if (polyhedron.equals("Octahedron")) sum += 8;
else if (polyhedron.equals("Dodecahedron")) sum += 12;
else if (polyhedron.equals("Icosahedron")) sum += 20;
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
4f311201a0a679f7140ed13055ce2b59
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class Polyhedrons {
public static void main(String args[]) {
String[] arr =new String[5];
arr[0] = "Tetrahedron";
arr[1] = "Cube";
arr[2] = "Octahedron";
arr[3] = "Dodecahedron";
arr[4] = "Icosahedron";
int[] arrM = {4,6,8,12,20};
int n;
Scanner s= new Scanner(System.in);
n=s.nextInt();
String[] arr1=new String[n+1];
for(int i=0;i<n;i++)
arr1[i] = s.next();
int result=0;
for(int i=0;i<n;i++) {
for(int j=0;j<5;j++) {
if(arr1[i].equals(arr[j])) {
result += arrM[j];
break;
}
}
}
s.close();
System.out.println(result);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
9b05642c47452d843c470f620f119041
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(), total = 0;
String[] names = {"Tetrahedron", "Cube", "Octahedron", "Dodecahedron", "Icosahedron"};
int[] numFaces = {4, 6, 8, 12, 20};
while (n-- > 0) {
total += numFaces[Arrays.asList(names).indexOf(scanner.next())];
}
System.out.println(total);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
c194f4160bc949f0b9676df36fb07dc9
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int total = 0;
while (n-- > 0) {
String name = scanner.next();
switch (name) {
case "Tetrahedron":
total += 4;
break;
case "Cube":
total += 6;
break;
case "Octahedron":
total += 8;
break;
case "Dodecahedron":
total += 12;
break;
case "Icosahedron":
total += 20;
break;
default:
break;
}
}
System.out.println(total);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
8fd1a463bed8d0c37e0720f6362c9e2f
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String[] names = {"Tetrahedron", "Cube", "Octahedron", "Dodecahedron", "Icosahedron"};
int[] numFaces = {4, 6, 8, 12, 20};
int total = 0;
while (n-- > 0) {
String name = scanner.next();
for (int i = 0; i < 5; i++) {
if(names[i].equals(name)) {
total += numFaces[i];
}
}
}
System.out.println(total);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
89427ac98d745a1edfdca6be2f91a04c
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class task5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
String a = sc.next();
switch (a) {
case "Tetrahedron":
count += 4;
break;
case "Cube":
count += 6;
break;
case "Octahedron":
count += 8;
break;
case "Dodecahedron":
count += 12;
break;
default:
count += 20;
}
}
System.out.println(count);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
9255bd6c2c8a98d5df4c6f85b2b2b4fc
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
String[] polyhedrons = new String[n];
int faceCounter = 0;
for (int i = 0; i < n; ++i) {
polyhedrons[i] = scanner.nextLine();
faceCounter += polyhedronNameToNumberOfFaces(polyhedrons[i]);
}
System.out.println(faceCounter);
}
private static int polyhedronNameToNumberOfFaces(String name) {
switch(name) {
case "Tetrahedron":
return 4;
case "Cube":
return 6;
case "Octahedron":
return 8;
case "Dodecahedron":
return 12;
case "Icosahedron":
return 20;
default:
return -1;
}
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
7a4ff005db256a0c7559773bdae4c650
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class JavaApplication123 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int k=s.nextInt();int sum=0;
for (int i = 0; i < k+1; i++) {
String s1=s.nextLine();
if(s1.equals("Cube")){sum+=6;}
else if(s1.equals("Tetrahedron")){sum+=4;}
else if(s1.equals("Octahedron")){sum+=8;}
else if(s1.equals("Dodecahedron")){sum+=12;}
else if(s1.equals("Icosahedron")){sum+=20;}
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
24499ac5850127140254d1885e96e746
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class JavaApplication123 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int k=s.nextInt();int sum=0;
for (int i = 0; i < k+1; i++) {
String s1=s.nextLine();
if(s1.equals("Cube"))
{sum+=6;}
else if(s1.equals("Tetrahedron")){sum+=4;}
else if(s1.equals("Octahedron")){sum+=8;}
else if(s1.equals("Dodecahedron")){sum+=12;}
else if(s1.equals("Icosahedron")){sum+=20;}
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
874afed3614c65fa9dca13c0fe160a41
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class polygons
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
int sum=0;
String poly="";
for(int i=0;i<=n;i++)
{
poly=obj.nextLine();
if((poly).equals("Tetrahedron"))
sum+=4;
if((poly).equals("Cube"))
sum+=6;
if((poly).equals("Octahedron"))
sum+=8;
if((poly).equals("Dodecahedron"))
sum+=12;
if((poly).equals("Icosahedron"))
sum+=20;
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
1e33c56b2b1121a6c8ec643f30cd2cdc
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
import java.io.*;
/*
Although copied but copying snippet does'nt Gurantee AC :-)
~~~~~~~~ ksj ~~~~~~~
*/
//Did I need Public ??????????????/
public class Prob {
public static int max = (int) (1e9+7);
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();
}
public static long xl,yl,z1,al,bl,cl,dl,el;
public static int x,y,z,a,b,c,d,e,T;
public static ArrayList<Integer> factor[]=new ArrayList[100001];
///>>>>> |+++ START FROM HERE BRO'
///
public static void solve() {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
long count=0;
T=in.nextInt();
// Here we go ......................... ((((((be calm))))))
while(T-->0){
String str=in.nextLine();
if(str.equals("Tetrahedron")){count+=4;}
if(str.equals("Cube")){count+=6;}
if(str.equals("Icosahedron")){count+=20;}
if(str.equals("Dodecahedron")){count+=12;}
if(str.equals("Octahedron")){count+=8;}
}
out.println(""+count);
out.close();
}
// for pair value use for i> adjecnt ii> weigth iii> cost
static class Node {
int i,dis;
Node(int i, int dis){
this.i=i; this.dis=dis;
}
}
public static Queue<Integer> q=new LinkedList<Integer>();
//PriorityQueue p=new PriorityQueue<Integer>(capacity,comparable{necessary of want to customize})
public static boolean v[]=new boolean[a];
public void Bfs(ArrayList<Integer> g[],int s,boolean v[]){
Arrays.fill(v,false);
q.add(s);
v[s]=false;
int t,size,t1;
while(!q.isEmpty()){
t=q.poll();
size=g[t].size();
for(int i=0;i<size;i++){
//mark its all adjecent...
if(v[g[t].get(i)]==false){
t1=g[t].get(i);
q.add(t1);
}
}
}
}
/*------------------------------------------Pair ----------------------Modified ------------------------->>>>>>>>*/
static class Pair implements Comparable<Pair>{
int x,y,i;
Pair (int x,int y,int i){
this.x=x;
this.y=y;
this.i=i;
}
Pair (int x,int y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
if(this.x!=o.x) return Integer.compare(this.x,o.x);
else return Integer.compare(this.y,o.y);
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y && p.i==i;
}
return false;
}
public int hashCode() {
return new Integer(x).hashCode() * 31 + new Integer(y).hashCode()+new Integer(i).hashCode()*37;
}
}
//>>>>>>>>>>>>>>>>>>>>>____________________________________________END
//XXXXXXXXXXXXX Library funtion --------------- Don't Cheat :-> use ur's ________________________________
public void factor(){
//initialitation ...........
for(int i=1;i<100001;i++){factor[i]=new ArrayList<Integer>();}
factor[1].add(1);
for(int i=1;i<316;i++){
for(int j=2;j<100001;j+=i){
factor[j].add(i);
}
}
}
public static boolean isPol(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
//_________________________________IMPO___________________________________
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
//_________________________________________________________________________
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
//___________________________Fast-Input_Output-------------------*******************
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
////////// ~ BSS ittu sa hi hai :-) ~
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
b40ab56c01e5fb80e30c32422017aee6
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(f.readLine());
int ans = 0;
for(int i = 0; i < n; i++) {
char x = f.readLine().charAt(0);
if(x == 'I') {
ans += 20;
} else if(x == 'D') {
ans += 12;
} else if(x == 'O') {
ans += 8;
} else if(x == 'C') {
ans += 6;
} else {
ans += 4;
}
}
System.out.println(ans);
f.close();
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
66f219b7bacff0c756c24fa1609b73ea
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Main
{
public static void main(String ar[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
s.nextLine();
int c=0;
for(int i=0;i<n;i++)
{
String str=s.nextLine();
if(str.equals("Tetrahedron"))
c=c+4;
else if(str.equals("Cube"))
c=c+6;
else if(str.equals("Octahedron"))
c=c+8;
else if(str.equals("Dodecahedron"))
c=c+12;
else if(str.equals("Icosahedron"))
c=c+20;
}
System.out.println(c);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
492272686b01c4815caa3b51b58cb203
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class codeForce {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
s.nextLine();
int number = 0;
while(n!=0) {
String input = s.nextLine();
switch(Character.toUpperCase(input.charAt(0)))
{
case 'T':
number = number + 4;
break;
case 'C':
number = number + 6;
break;
case 'O':
number = number + 8;
break;
case 'D':
number = number + 12;
break;
case 'I':
number = number + 20;
break;
}
n--;
}
System.out.println(number);
s.close();
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
1530f12c07a32b1638e51d402a2997d8
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class c1
{
public static void main(String[] args) throws Exception{
Scanner in=new Scanner(System.in);
long n=in.nextLong();
long sum=0;
in.nextLine();
while(n!=0)
{
String s=in.nextLine();
if(s.equals("Tetrahedron"))
sum+=4;
else if(s.equals("Cube"))
sum+=6;
else if(s.equals("Octahedron"))
sum+=8;
else if(s.equals("Dodecahedron"))
sum+=12;
else
sum+=20;
n--;
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
d7cb61d1de48ef4f385aa8f685be9d57
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.io.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Main
{
public static void main(String[] args) {
HashMap<String, Integer> mapref = new HashMap<String, Integer>();
initmap(mapref);
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
long a=stdin.nextInt();
HashMap<String, Integer> map = new HashMap<String, Integer>();
while(stdin.hasNext()){
String val = stdin.next();
if(map.containsKey(val)){
map.put(val,(map.get(val)+mapref.get(val)));
a--;
}
else map.put(val,mapref.get(val));
if (a == map.size()) {
break;
}
}
System.out.println(test(map));
}
public static int test(HashMap<String, Integer> l)
{ int sum=0;
Set set = l.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
sum=sum+Integer.parseInt(mentry.getValue().toString());
}
return sum;
}
public static void initmap(HashMap<String, Integer> mapref)
{mapref.put("Tetrahedron",4);
mapref.put("Cube",6 );
mapref.put("Octahedron",8);
mapref.put("Dodecahedron",12);
mapref.put("Icosahedron",20);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
f3b33c2ad9b0a0fdd4e634bd8f81c9f3
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.io.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Main
{
public static void main(String[] args) {
HashMap<String, Integer> mapref = new HashMap<String, Integer>();
initmap(mapref);
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
long a=stdin.nextInt();
HashMap<String, Integer> map = new HashMap<String, Integer>();
while(stdin.hasNext()){
String val = stdin.next();
if(map.containsKey(val)){
int alpha =map.get(val);
map.remove(val);
map.put(val,(alpha+mapref.get(val)));
a--;
}
else map.put(val,mapref.get(val));
if (a == map.size()) {
break;
}
}
System.out.println(test(map));
}
public static int test(HashMap<String, Integer> l)
{ int sum=0;
Set set = l.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
sum=sum+Integer.parseInt(mentry.getValue().toString());
}
return sum;
}
public static void initmap(HashMap<String, Integer> mapref)
{mapref.put("Tetrahedron",4);
mapref.put("Cube",6 );
mapref.put("Octahedron",8);
mapref.put("Dodecahedron",12);
mapref.put("Icosahedron",20);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
425456bc32b65148dcd2ec5dd7791338
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
int k = 0;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = in.next();
}
for (int i = 0; i < n; i++) {
if ("Tetrahedron".equals(names[i])) {
k += 4;
} else if ("Cube".equals(names[i])) {
k += 6;
} else if ("Octahedron".equals(names[i])) {
k += 8;
} else if ("Dodecahedron".equals(names[i])) {
k += 12;
} else if ("Icosahedron".equals(names[i])) {
k += 20;
}
}
System.out.print(k);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
488433f4dc74f795a17afa77240b505d
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
int k = 0;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = in.next();
}
for (int i = 0; i < n; i++) {
if ("Tetrahedron".equals(names[i])) {
k += 4;
} else if ("Cube".equals(names[i])) {
k += 6;
} else if ("Octahedron".equals(names[i])) {
k += 8;
} else if ("Dodecahedron".equals(names[i])) {
k += 12;
} else if ("Icosahedron".equals(names[i])) {
k += 20;
}
}
System.out.print(k);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
2d2e0930cd41c5005100c5b4d426af5e
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
public class t1{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
String[] ary=new String[n];
scan.nextLine();
for(int i=0;i<n;i++){
ary[i]=scan.nextLine();
}
int sum=0;
for(int i=0;i<n;i++){
switch(ary[i]){
case "Tetrahedron":
sum=sum+4;
break;
case "Cube":
sum=sum+6;
break;
case "Octahedron":
sum=sum+8;
break;
case "Dodecahedron":
sum=sum+12;
break;
case "Icosahedron":
sum=sum+20;
break;
default:
sum=sum;
}
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
f12068ad802f53bc9e058603acc04a7e
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
public class t1{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
scan.nextLine();
int sum=0;
int k=0;
//System.out.println(n);
while(k<n){
String str=scan.nextLine();
switch(str){
case "Tetrahedron":
sum=sum+4;
break;
case "Cube":
sum=sum+6;
break;
case "Octahedron":
sum=sum+8;
break;
case "Dodecahedron":
sum=sum+12;
break;
case "Icosahedron":
sum=sum+20;
break;
default:
sum=sum;
}
k++;
str="";
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
ace5ac2fdf7ec60396d65b699112239d
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Tetrahedron", 4);
map.put("Cube", 6);
map.put("Octahedron", 8);
map.put("Dodecahedron", 12);
map.put("Icosahedron", 20);
//System.out.println(map.get("Icosahedron"));
int test = 0;
Scanner scan = new Scanner(System.in);
int value = scan.nextInt();
String valeur;
for (int i = 0; i < value; i++) {
//Scanner scan2 = new Scanner(System.in);
valeur = scan.next();
test += map.get(valeur);
}
System.out.println(test);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
c4133a7b68668dd6de705e7236d766f9
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.io.*;
import java.util.Scanner;
public class Antonpoly {
public static void main(String[] args) {
// Scanner myObj = new Scanner(System.in);
Scanner line = new Scanner(System.in);
int n = line.nextInt();
int res = 0;
for (int i = 0; i < n; i++) {
String s = line.next();
if (s.equals("Tetrahedron")) res += 4;
else if (s.equals("Cube")) res += 6;
else if (s.equals("Octahedron")) res += 8;
else if (s.equals("Dodecahedron")) res += 12;
else if (s.equals("Icosahedron")) res += 20;
}
System.out.println(res);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
c516ba2c03f7572c3e90639eecf911c2
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Bob{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int sum=0;
for(int i=0;i<n+1;i++)
{
String s=in.nextLine();
if(s.equals("Tetrahedron")){
sum=sum+4;
}
else if(s.equals("Cube")){
sum=sum+6;
}
else if(s.equals("Octahedron"))
{
sum=sum+8;
}
else if(s.equals("Dodecahedron"))
{
sum=sum+12;
}
else if(s.equals("Icosahedron"))
{
sum=sum+20;
}}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
e33be340c3afdfabfdb3f5ecce944582
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String temp;
int result = 0;
for (int i = 0; i < a; i++) {
temp = input.next();
if (temp.equals("Tetrahedron"))
result = result + 4;
else if (temp.equals("Cube"))
result += 6;
else if (temp.equals("Octahedron"))
result += 8;
else if (temp.equals("Dodecahedron"))
result += 12;
else if (temp.equals("Icosahedron"))
result += 20;
}
System.out.println(result);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
74cbcce371e2900461a073940ce9cbab
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class Solutions {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n = kbd.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
String P=kbd.next();
if(P.equals("Tetrahedron"))
sum+=4;
else if(P.equals("Cube"))
sum+=6;
else if(P.equals("Octahedron"))
sum+=8;
else if(P.equals("Dodecahedron"))
sum+=12;
else if(P.equals("Icosahedron"))
sum+=20;
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
6ab6cfc5ec8e3204b6044f375fed3359
|
train_001.jsonl
|
1489590300
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
256 megabytes
|
import java.util.*;
public class AntonAndPolyhedrons {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n = kbd.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
String P=kbd.next();
if(P.equals("Tetrahedron"))
sum+=4;
else if(P.equals("Cube"))
sum+=6;
else if(P.equals("Octahedron"))
sum+=8;
else if(P.equals("Dodecahedron"))
sum+=12;
else if(P.equals("Icosahedron"))
sum+=20;
}
System.out.println(sum);
}
}
|
Java
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
2 seconds
|
["42", "28"]
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces.
|
Java 8
|
standard input
|
[
"implementation",
"strings"
] |
e6689123fefea251555e0e096f58f6d1
|
The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
| 800
|
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
|
standard output
| |
PASSED
|
50fbe7b2f90f5dce0aa24eecd3b2415a
|
train_001.jsonl
|
1506791100
|
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.
|
256 megabytes
|
import java.io.*;
import java.math.*;
import java.util.*;
public class E_buyLowSellHigh {
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] arr = sc.nextIntArray(n);
PriorityQueue<Integer> pq = new PriorityQueue<>();
long count = 0;
for (int i = 0; i < arr.length; i++) {
pq.add(arr[i]);
if ((int)pq.peek() < arr[i]) {
pq.add(arr[i]);
count += arr[i]-(int)pq.poll();
}
//pw.println(pq);
//pw.println("count = " + count);
}
pw.println(count);
pw.close();
}
static class FastScanner {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastScanner(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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
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 boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n){
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n){
int array[]=nextIntArray(n);
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int i = 0; i < n; i++){
pq.add(array[i]);
}
int[] out = new int[n];
for(int i = 0; i < n; i++){
out[i] = pq.poll();
}
return out;
}
public int[] nextSumIntArray(int n){
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public ArrayList<Integer>[] nextGraph(int n, int m){
ArrayList<Integer>[] adj = new ArrayList[n];
for(int i = 0; i < n; i++){
adj[i] = new ArrayList<Integer>();
}
for(int i = 0; i < m; i++){
int u = nextInt(); int v = nextInt();
u--; v--;
adj[u].add(v); adj[v].add(u);
}
return adj;
}
public ArrayList<Integer>[] nextTree(int n){
return nextGraph(n, n-1);
}
public long[] nextLongArray(int n){
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n){
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n){
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
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;
}
}
}
|
Java
|
["9\n10 5 4 7 9 12 6 2 10", "20\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4"]
|
2 seconds
|
["20", "41"]
|
NoteIn the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is β-β5β-β4β+β9β+β12β-β2β+β10β=β20.
|
Java 11
|
standard input
|
[
"data structures",
"greedy"
] |
994bfacedc61a4a67c0997011cadb333
|
Input begins with an integer N (2ββ€βNββ€β3Β·105), the number of days. Following this is a line with exactly N integers p1,βp2,β...,βpN (1ββ€βpiββ€β106). The price of one share of stock on the i-th day is given by pi.
| 2,400
|
Print the maximum amount of money you can end up with at the end of N days.
|
standard output
| |
PASSED
|
d2eaf915dcabc470cba4a33f2148a2f2
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author master
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner x = new Scanner (System.in);
int n = x.nextInt(), i, j ;
int d = x.nextInt() ;
long res = 0 ;
int arr [] = new int [n];
boolean t [] = new boolean [n];
for (i = 0 ; i < n ; i++)
arr[i] = x.nextInt();
j = 0 ;
i = 0 ;
long c ;
while ( i < n )
if(arr[i] - arr[j] <= d )
{
c= i-j ;
res +=c*(c-1)/2;
i++;
}
else
while( arr[i] - arr[j] > d )
j++;
System.out.print(res);
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
19bfa275df26511e3d3181e5f8a73f15
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author master
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner x = new Scanner (System.in);
int n = x.nextInt(), i, j ;
int d = x.nextInt() ;
long res = 0 ;
int arr [] = new int [n];
boolean t [] = new boolean [n];
for (i = 0 ; i < n ; i++)
arr[i] = x.nextInt();
j = 0 ;
i = 0 ;
/*while ( i < n )
if(arr[i] - arr[j] <= d )
{
res +=((i-j)*(i-j-1)/2);
i++;
}
else
while( arr[i] - arr[j] > d )
j++;
*/
long cur ;
for( ;i<n;i++) {
while(arr[i]-arr[j]>d) j++;
cur = i-j ;
res += cur*(cur-1)/2;
}
System.out.print(res);
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
87ae50a044737a8b285c875a687d824c
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.Math;
public class Main{
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter writer;
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static String nexts() throws IOException {
tokenizer = new StringTokenizer(reader.readLine());
String s="";
while (tokenizer.hasMoreTokens()) {
s+=tokenizer.nextElement()+" ";
}
return s;
}
//String str=nextToken();
//String[] s = str.split("\\s+");
public static int gcd(int x, int y){
if (y == 0) return x; else return gcd(y, x % y);
}
public static boolean isPrime(int n)
{
// Corner cases
if (n <= 1){
return false; }
if (n <= 3){
return true; }
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0){
return false; }
for (int i = 5; i * i <= n; i = i + 6) { //Checking 6i+1 & 6i-1
if (n % i == 0 || n % (i + 2) == 0) {
return false; }
}
//O(sqrt(n))
return true;
}
public static void shuffle(int[] A) {
for (int i = 0; i < A.length; i++) {
int j = (int)(i * Math.random());
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
public static long power(int x, long n)
{
long mod = 1000000007;
if (n == 0) {
return 1;
}
long pow = power(x, n / 2);
if ((n & 1) == 1) {
return (x * pow * pow)%mod;
}
return (pow * pow)%mod;
}
static long ncr(int n, int k)
{
long res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k) {
k = n - k;
}
// Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1]
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static int first(int arr[], int low, int high, int x, int n) //Returns first index of x in sorted arr else -1
{
if(high >= low)
{
int mid =low + (high - low)/2;
if( ( mid == 0 || x > arr[mid-1]) && arr[mid] == x)
return mid;
else if(x > arr[mid])
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid -1), x, n);
}
return -1;
}
static int last(int arr[], int low, int high, int x, int n) //Returns last index of x in sorted arr else -1
{
if(high >= low)
{
int mid = low + (high - low)/2;
if( ( mid == n-1 || x < arr[mid+1]) && arr[mid] == x )
return mid;
else if(x < arr[mid])
return last(arr, low, (mid -1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
static int binarys(int[] arr, int l, int r, int x){
while(l<=r){
int mid = l+(r-l)/2;
if(arr[mid]==x){
return x;
}
if(arr[mid]<x){
l=mid+1;
}
else{
r=mid-1;
}
}
return -1;
}
static class R implements Comparable<R>{
int x, y;
public R(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(R o) {
return x-o.x; //Increasing order(Which is usually required)
}
}
// int t=a[i];
// a[i]=a[j];
// a[j]=t;
//double d=Math.sqrt(Math.pow(Math.abs(x2-x1),2)+Math.pow(Math.abs(y2-y1),2));
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
private static void solve() throws IOException {
// int t = nextInt();
// while(t-->0){
//long n = nextLong();
//String s= nextToken();
//long[] a=new long[n];
//ArrayList<Integer> ar=new ArrayList<Integer>();
//HashSet<Integer> set=new HashSet<Integer>();
//HashMap<Integer,String> h=new HashMap<Integer,String>();
//R[] a1=new R[n];
//char[] c=nextToken().toCharArray();
int n = nextInt();
long d = nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=nextInt();
}
int j=0;
long ans=0;
for(int i=2;i<n;i++){
while(a[i]-a[j]>d){
j++;
}
long k=i-j+1-1;
ans+=k*(k-1)/2;
}
writer.println(ans);
}
//}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
0bf7dd955d91a6358a61ab750cca9526
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
public static long bs (int[] arr, int i,int l, int h, int d){
if (h >= l) {
int mid = (h+l) / 2;
if(mid==arr.length-1) return mid;
if(mid<arr.length-1){
if (arr[mid]-arr[i] <= d && arr[mid+1]-arr[i]>d)
return mid;
if (arr[mid]-arr[i] > d)
return bs(arr,i, l, mid - 1, d);
return bs(arr,i, mid + 1, h, d);
} }
return -1;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
int[] arr= new int[n];
long ans =0;
st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++)
{
arr[i] = Integer.parseInt(st.nextToken());
}
for(int i =0; i< n-2 ;i++){
long z = bs(arr,i,i,n-1,d);
if(z-i>=2) ans+=((z-1-i)*(z-i)/2);
}
System.out.println(ans);
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
ca1798c2ca7038abb5efcbdeb600c881
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class loser
{
static class InputReader {
public BufferedReader br;
public StringTokenizer token;
public InputReader(InputStream stream)
{
br=new BufferedReader(new InputStreamReader(stream),32768);
token=null;
}
public String next()
{
while(token==null || !token.hasMoreTokens())
{
try
{
token=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
return token.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
static class card{
long g;
int ess;
public card(long ch,int i)
{
this.g=ch;
this.ess=i;
}
}
static class sort implements Comparator<card>
{
public int compare(card o1,card o2)
{
if(o1.ess!=o2.ess)
return (o1.ess-o2.ess);
else
return (int)(o1.g-o2.g);
}
}
static void shuffle(long a[])
{
List<Long> l=new ArrayList<>();
for(int i=0;i<a.length;i++)
l.add(a[i]);
Collections.shuffle(l);
for(int i=0;i<a.length;i++)
a[i]=l.get(i);
}
/*static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
static boolean valid(int i,int j,int r,int c)
{
if(i<r && i>=0 && j<c && j>=0)
return true;
else
return false;
}*/
public static void main(String[] args)
{
InputReader sc=new InputReader(System.in);
int n=sc.nextInt();
long d=sc.nextLong();
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
long sum=0;int j=0;
for(int i=0;i<n;i++)
{
while(a[i]-a[j]>d)
j++;
long t=i-j;
sum+=(t*(t-1))/2;
}
System.out.println(sum);
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
cf243a975e3ed866495b5183a4b14400
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.util.*;
public class Solution{
public static void main(String arg[])
{
Scanner io=new Scanner(System.in);
int n=io.nextInt(),d=io.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=io.nextInt();
long count=0;
int j=0;
for(int i=0;i<n;i++)
{
for(;j+1<n && arr[j+1]-arr[i]<=d;)j++;
long t1=j-i;
count+=(t1)*(t1-1)/2;
}
System.out.println(""+count);
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
26dc26b750938a3211047a463e2b54d2
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
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.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Problem1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt(), d = in.nextInt();
int[] a = new int[n];
long ans = 0;
for(int i = 0; i < n; ++i)
{
a[i] = in.nextInt();
}
int beg = 0, end;
long k;
for(end = 0; end < n; ++end)
{
while(a[end] - a[beg] > d)
{
++beg;
}
k = end - beg - 1;
ans += k*(k+1)/2;
}
out.println(ans);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
e9923c3d243262d650c0552138479835
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{ static PrintWriter out=new PrintWriter(System.out);
static FastScanner in = new FastScanner(System.in);
static class FastScanner {BufferedReader br;StringTokenizer stok;FastScanner(InputStream is) {br = new BufferedReader(new InputStreamReader(is));}
String next() throws IOException {while (stok == null || !stok.hasMoreTokens()) {String s = br.readLine();if (s == null) {return null;}
stok = new StringTokenizer(s);}return stok.nextToken();}
int ni() throws IOException {
return Integer.parseInt(next());}
long nl() throws IOException {
return Long.parseLong(next());}
double nd() throws IOException {
return Double.parseDouble(next());}
char nc() throws IOException {return (char) (br.read());}
String ns() throws IOException {return br.readLine();}
int[] nia(int n) throws IOException{int a[] = new int[n];for (int i = 0; i < n; i++)a[i] = ni();return a;}
long[] nla(int n) throws IOException {
long a[] = new long[n];for (int i = 0; i < n; i++)a[i] = nl();return a;}
double[] nda(int n)throws IOException {
double a[] = new double[n];for (int i = 0; i < n; i++) a[i] = nd(); return a;}
int [][] imat(int n,int m) throws IOException
{ int mat[][]=new int[n][m];for(int i=0;i<n;i++){ for(int j=0;j<m;j++)mat[i][j]=ni();}return mat;}
}
static long mod=Long.MAX_VALUE;
public static void main (String[] args) throws java.lang.Exception
{ int i,j;
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
/* if(hm.containsKey(z))
hm.put(z,hm.get(z)+1);
else
hm.put(z,1);
*/
ArrayList<Integer> arr=new ArrayList<Integer>();
HashSet<Integer> set=new HashSet<Integer>();
PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
int n=in.ni();
int d=in.ni();
int a[]=in.nia(n);
long ans=0;
int counter1=0,counter2=2;
while(counter2<n)
{
if(a[counter2]-a[counter1]<=d)
{
long z=counter2-counter1;
ans+=z*(z-1)/2;
counter2++;
}
else
counter1++;
}
out.println(ans);
out.close();
}
static long gcd(long a,long b)
{ if(b==0)
return a;
return gcd(b,a%b);
}
static long exponent(long a,long n)
{ long ans=1;
while(n!=0)
{ if(n%2==1)
ans=(ans*a)%mod;
a=(a*a)%mod;
n=n>>1;
}
return ans;
}
static int binarySearch(int a[], int item, int low, int high)
{ if (high <= low)
return (item > a[low])? (low + 1): low;
int mid = (low + high)/2;
if(item == a[mid])
return mid+1;
if(item > a[mid])
return binarySearch(a, item, mid+1, high);
return binarySearch(a, item, low, mid-1);
}
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2];
for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l;
while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else{ arr[k] = R[j]; j++; } k++; } while (i < n1){ arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; }
}
static void Sort(int arr[], int l, int r) {
if (l < r) { int m = (l+r)/2; Sort(arr, l, m); Sort(arr , m+1, r); merge(arr, l, m, r); } }
static void sort(int a[])
{Sort(a,0,a.length-1);}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
7176d417143f895c7f9523b107835cae
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author maheshwari29
*/
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);
APointsOnLine solver = new APointsOnLine();
solver.solve(1, in, out);
out.close();
}
static class APointsOnLine {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int i, j;
int n = in.ni();
int k = in.ni();
int a[] = in.nia(n);
int ptr = 0, ptr2 = 2;
long ans = 0;
while (ptr2 < n) {
if (a[ptr2] - a[ptr] <= k) {
long z = (long) (ptr2 - ptr);
ans += z * (z - 1) / 2;
ptr2++;
} else
ptr++;
}
out.println(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int ni() {
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 int[] nia(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = ni();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
63071f30656b324da15f81b60f12828d
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static int n, d;
static int[] X;
public static void main(String[] args) throws IOException {
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
d = Integer.parseInt(st.nextToken());
X = new int[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
X[i] = Integer.parseInt(st.nextToken());
}
BigInteger res = BigInteger.ZERO;
int a, b, m;
long best;
for(int i = 0; i < n; ++i) {
best = i; a = i+2; b = n-1;
while (a <= b) {
m = (a+b) / 2;
if (X[m] - X[i] <= d) {
best = Math.max(i, m);
a = m + 1;
} else {
b = m - 1;
}
}
if (best - i > 1) {
long inc = ((best-i)*(best-i-1)) / 2;
res = res.add(new BigInteger(String.valueOf(inc)));
}
}
System.out.println(res);
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
8f06b4506c123aeedec202578da6181c
|
train_001.jsonl
|
1354807800
|
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.
|
256 megabytes
|
import java.awt.List;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.TimeZone;
public class C {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
InputStream inputstream = System.in;
OutputStream outputstream = System.out;
FastReader in = new FastReader(inputstream);
PrintWriter out = new PrintWriter(outputstream);
TaskA solver = new TaskA();
// int testcase = in.ni();
for (int i = 0; i < 1; i++)
solver.solve(i, in, out);
out.close();
}
}
class TaskA {
public void solve(int testnumber, FastReader in, PrintWriter out) {
int n = in.ni();
int d = in.ni();
int arr[] = in.iArr(n);
long points = 0;
for(int left = 0, right = 0;left<n;left++){
right = Math.max(left, right);
while(right < (n-1) && arr[right+1] - arr[left] <= d)
right++;
long pt = right - left;
points += pt * (pt - 1) / 2;
}
out.println(points);
}
}
class FastReader {
public InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public FastReader() {
}
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 ni() {
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 ns() {
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 isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] iArr(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String next() {
return ns();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
Java
|
["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"]
|
2 seconds
|
["4", "2", "1"]
|
NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
|
Java 8
|
standard input
|
[
"combinatorics",
"binary search",
"two pointers"
] |
1f6491999bec55cb8d960181e830f4c8
|
The first line contains two integers: n and d (1ββ€βnββ€β105;Β 1ββ€βdββ€β109). The next line contains n integers x1,βx2,β...,βxn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.
| 1,300
|
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
| |
PASSED
|
b9ca0326b700f6881e82c4621cddc4a6
|
train_001.jsonl
|
1545143700
|
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).Note that Vova can't put bricks vertically.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class d
{
public static void main(String[] Args) throws Exception
{
FastScanner sc = new FastScanner(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
Node cur = null;
Node head = null;
int[] vals = new int[n];
for (int i = 0; i < n; i++)
{
int h;
vals[i] = (h = (sc.nextInt()));
if (cur == null)
{
head = new Node();
head.par = h;
cur = head;
}
if (cur.par == h)
{
cur.sum++;
}
else
{
Node prev = cur;
cur = new Node();
cur.par = h;
cur.sum = 1;
prev.next = cur;
cur.prev = prev;
}
}
if (n == 1)
{
out.println("YES");
out.close();
return;
}
boolean good3 = (vals[0] >= vals[1] && vals[n - 2] <= vals[n - 1]);
for (int i = 1; i < n - 1; i++)
{
if (vals[i] < vals[i - 1] && vals[i] < vals[i + 1])
good3 = false;
}
if (!good3)
{
out.println("NO");
out.close();
return;
}
cur = head;
while (cur != null)
{
//out.println(cur.sum);
cur = cur.next;
}
cur = head;
while (cur.next != null || cur.merge())
{
while (cur.merge());
if (cur.next != null)
cur = cur.next;
}
if (cur.next == null && cur.prev == null)
out.println("YES");
else
out.println("NO");
out.close();
}
public static int oo = 1000000010;
public static class Node{
int sum;
int par;
Node next, prev;
Node()
{
next = null;
prev = null;
sum = 0;
par = 0;
}
public boolean merge()
{
if ((sum & 1) == 1)
return false;
int nh = oo;
if (prev != null && prev.par > par)
nh = prev.par;
if (next != null && next.par > par && next.par < nh)
nh = next.par;
if (nh == oo)
return false;
if (prev != null && nh == prev.par){
sum += prev.sum;
prev = prev.prev;
if (prev != null)
prev.next = this;
}
if (next != null && nh == next.par){
sum += next.sum;
next = next.next;
if (next != null)
next.prev = this;
}
par = nh;
return true;
}
}
public static class FastScanner
{
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream in) throws Exception
{
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer(br.readLine());
}
String next() throws Exception
{
if (st.hasMoreTokens())
return st.nextToken();
st = new StringTokenizer(br.readLine());
return next();
}
int nextInt() throws Exception
{
return Integer.parseInt(next());
}
}
}
|
Java
|
["5\n2 1 1 2 5", "3\n4 5 3", "2\n10 10"]
|
2 seconds
|
["YES", "NO", "YES"]
|
NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put no bricks in the wall.In the third example the wall is already complete.
|
Java 8
|
standard input
|
[
"data structures",
"implementation"
] |
f73b832bbbfe688e378f3d693cfa23b8
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) β the initial heights of the parts of the wall.
| 2,200
|
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.
|
standard output
| |
PASSED
|
d22d7d023d435af5ead013f07d8d1191
|
train_001.jsonl
|
1545143700
|
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).Note that Vova can't put bricks vertically.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?
|
256 megabytes
|
import com.sun.org.apache.xpath.internal.SourceTree;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.IntStream;
/**
* Created by Mach on 15.12.2018.
*/
public class round56a {
static boolean nores=false;
static int maxColor=0;
public static void main(String[] args) {
Reader56a r = new Reader56a();
r.init(System.in);
int n = r.nextInt();
if (n==1) {System.out.println("YES"); return;}
int a[]=new int[n];
long sum=0;
int max=0;
int min=Integer.MAX_VALUE;
Integer start;
for (int i=0; i<n; i++) {
a[i]=r.nextInt();
if(a[i]>max) max=a[i];
if(a[i]<min) min=a[i];
sum=sum+a[i];
}
if (min==max) {System.out.println("YES"); return;}
Deque<Integer> dq=new LinkedList<>();
int level=0;
int temp;
int i=0;
for (; i < n-1; i++) {
if (!dq.isEmpty())
if (dq.peekLast()==a[i]) {dq.removeLast(); continue;}
if (a[i]==a[i+1]) {i++; continue;}
if (a[i]<a[i+1]) {System.out.println("NO"); return;};
dq.addLast(a[i]);
}
// System.out.println(i);
if (i==n-1)
if (!dq.isEmpty())
{if (dq.peekLast()==a[i]) {dq.removeLast();} else {dq.addLast(a[i]);}}
else {dq.addLast(a[i]);}
// System.out.println(dq.size());
if (n%2==1) if (dq.size()>0) if (dq.peekLast()!=max) {System.out.println("NO"); return;}
if (dq.size()==n%2) {System.out.println("YES");} else {System.out.println("NO");}
}
static int putBlock(int[] a, int n, int j, int max) {
// System.out.println(Arrays.toString(a)+" "+j+" "+max);
for (int i=j; i < n; i++) {
if (a[i]>=max) return i;
if (i==n-1) return -1;
if (a[i]<a[i+1]) return -1;
if (a[i]>a[i+1]) if (putBlock(a, n, i+1, a[i])==-1) return -1;
if (a[i]==a[i+1]) {a[i]=max; a[i+1]=max; i++; continue;}
}
return n;
}
}
class Node{
Node prev;
Node next;
int val;
Node() {this.val=-1;}
Node(int i) {
this.val=i;
}
}
class Reader56a {
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
try {
tokenizer = new StringTokenizer(
reader.readLine());
} catch(Exception e) {e.printStackTrace();}
}
return tokenizer.nextToken();
}
static int nextInt() {
return Integer.parseInt( next() );
}
static long nextLong(){ return Long.parseLong( next() );}
static double nextDouble() {
return Double.parseDouble( next() );
}
}
|
Java
|
["5\n2 1 1 2 5", "3\n4 5 3", "2\n10 10"]
|
2 seconds
|
["YES", "NO", "YES"]
|
NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put no bricks in the wall.In the third example the wall is already complete.
|
Java 8
|
standard input
|
[
"data structures",
"implementation"
] |
f73b832bbbfe688e378f3d693cfa23b8
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) β the initial heights of the parts of the wall.
| 2,200
|
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.
|
standard output
| |
PASSED
|
ecc2f1ced3bfbcb1d82d20892c3792d1
|
train_001.jsonl
|
1545143700
|
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).Note that Vova can't put bricks vertically.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
static class Task {
int NN = 100005;
int MOD = 998244353;
int INF = 2000000000;
int [] a;
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
a = new int[n];
int mx = 0;
for(int i=0;i<n;++i) {
a[i] = in.nextInt();
mx = Math.max(mx, a[i]);
}
for(int i=0;i<n;++i) {
a[i] = mx - a[i];
}
Map<Integer, List<Integer>> pos = new HashMap<>();
TreeSet<Integer> S = new TreeSet<>(
(j, i) ->
Integer.valueOf(i)
.compareTo(Integer.valueOf(j)));
for(int i=0;i<n;++i) {
List<Integer> L = new ArrayList<>();
if(pos.containsKey(a[i])) {
L = pos.get(a[i]);
}
L.add(i);
pos.put(a[i], L);
if(a[i] > 0) {
S.add(a[i]);
}
}
T = new int[n + 1];
for(int i=0;i<n;++i)
T[i] = 0;
for(int num: S) {
List<Integer> posList = pos.get(num);
if(posList.size()%2 != 0) {
out.println("NO");return;
}
for(int i=0;i<posList.size();i+=2) {
if(!isAdjacent(posList.get(i), posList.get(i + 1))) {
out.println("NO");return;
}
update(posList.get(i), 1, n);
update(posList.get(i + 1), 1, n);
}
}
out.println("YES");
}
int [] T;
void update(int idx, int val, int n) {
++idx;
while(idx <= n) {
T[idx] += val;
idx += idx&-idx;
}
}
int query(int idx) {
++idx;
int ret = 0 ;
while(idx > 0) {
ret += T[idx];
idx -= idx&-idx;
}
return ret;
}
boolean isAdjacent(int i, int j) {
if(j <= i)
return false;
if(j == i + 1)
return true;
int cnt = j - i - 1;
return query(j - 1) - query(i) == cnt;
}
}
static void prepareIO(boolean isFileIO) {
Task solver = new Task();
// Standard IO
if(!isFileIO) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver.solve(in, out);
out.close();
}
// File IO
else {
String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
InputReader fin = new InputReader(IPfilePath);
PrintWriter fout = null;
try {
fout = new PrintWriter(new File(OPfilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solver.solve(fin, fout);
fout.close();
}
}
public static void main(String[] args) {
prepareIO(false);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(String filePath) {
File file = new File(filePath);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["5\n2 1 1 2 5", "3\n4 5 3", "2\n10 10"]
|
2 seconds
|
["YES", "NO", "YES"]
|
NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put no bricks in the wall.In the third example the wall is already complete.
|
Java 8
|
standard input
|
[
"data structures",
"implementation"
] |
f73b832bbbfe688e378f3d693cfa23b8
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) β the initial heights of the parts of the wall.
| 2,200
|
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.
|
standard output
| |
PASSED
|
6312a2579ddd7c327616367d7a7ff2a4
|
train_001.jsonl
|
1545143700
|
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).Note that Vova can't put bricks vertically.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?
|
256 megabytes
|
//package codeforces;
import java.util.Scanner;
import java.util.Stack;
/**
* θ’«hackδΊ, ζ³ζ³θ¦ζδΉε
*/
public class CF527_D3_E {
public static void main(String ...args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Stack<Integer> stack = new Stack<>();
int max = -1;
for (int i = 0; i < n; i++) {
if (stack.isEmpty()) {
stack.push(arr[i]);
} else if (stack.peek() == arr[i]) {
stack.pop();
max = Math.max(arr[i], max);
} else if (stack.peek() > arr[i]){
stack.push(arr[i]);
} else {
System.out.println("NO");
return;
}
}
boolean result = stack.size() == 0 || (stack.size() == 1 && stack.peek() >= max);
System.out.println(result ? "YES" : "NO");
}
}
|
Java
|
["5\n2 1 1 2 5", "3\n4 5 3", "2\n10 10"]
|
2 seconds
|
["YES", "NO", "YES"]
|
NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put no bricks in the wall.In the third example the wall is already complete.
|
Java 8
|
standard input
|
[
"data structures",
"implementation"
] |
f73b832bbbfe688e378f3d693cfa23b8
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) β the initial heights of the parts of the wall.
| 2,200
|
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.
|
standard output
| |
PASSED
|
1eed65603656213f77012adb7b8420f7
|
train_001.jsonl
|
1596810900
|
This is an easier version of the problem E with smaller constraints.Twilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin.To hide the crucial information from evil eyes, pony elders cast a spell on the scroll. That spell adds exactly one letter in any place to each word it is cast on. To make the path to the knowledge more tangled elders chose some of words in the scroll and cast a spell on them.Twilight Sparkle knows that the elders admired the order in all things so the scroll original scroll contained words in lexicographically non-decreasing order. She is asked to delete one letter from some of the words of the scroll (to undo the spell) to get some version of the original scroll. Unfortunately, there may be more than one way to recover the ancient scroll. To not let the important knowledge slip by Twilight has to look through all variants of the original scroll and find the required one. To estimate the maximum time Twilight may spend on the work she needs to know the number of variants she has to look through. She asks you to find that number! Since that number can be very big, Twilight asks you to find it modulo $$$10^9+7$$$.It may occur that princess Celestia has sent a wrong scroll so the answer may not exist.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
|
256 megabytes
|
import java.io.*;
import java.lang.Math;
import java.util.*;
public class Main {
public BufferedReader in;
public PrintStream out;
public boolean log_enabled = false;
public boolean multiply_tests = false;
public static boolean do_gen_test = false;
public void gen_test() {
}
public int N;
public int[][] D;
public int[][] U;
public int[] D_cnt;
public String[] words;
public int [][] dfpos;
private class TestCase {
public int charAtPos(int k, int j)
{
return (j>=0) && (j<words[k].length()) ? (int)words[k].charAt(j) : 0;
}
public void get_d_list(String s, int k)
{
int i, cnt = 2, n = s.length();
for (i=1; i<n; i++)
{
if (s.charAt(i)!=s.charAt(i-1))
{
cnt ++;
}
}
D_cnt[k] = cnt;
D[k] = new int[cnt];
U[k] = new int[cnt];
int l = 0, r = cnt-1;
int u = 1;
for (i=0; i<n; i++)
{
if ((i+1<n)&&(s.charAt(i)==s.charAt(i+1)))
{
u++;
continue;
}
if ((i+1 == n) || s.charAt(i+1) < s.charAt(i))
{
U[k][l] = u;
D[k][l++] = i;
}
else
{
U[k][r] = u;
D[k][r--] = i;
}
u = 1;
}
D[k][l] = n;
U[k][l] = 1;
}
public int cmp(int k, int d1, int d2)
{
String w1 = words[k];
if (d1<w1.length())
{
w1 = w1.substring(0, d1).concat(
w1.substring(d1+1)
);
}
String w2 = words[k+1];
if (d2<w2.length())
{
w2 = w2.substring(0, d2).concat(
w2.substring(d2+1)
);
}
/*int c = _cmp(k, d1, d2);
c = _cmp(k, d1, d2);
return c;
*/
return w1.compareTo(w2);
}
public int _cmp(int k, int d1, int d2)
{
if (d1==d2)
{
if (dfpos[k][0]==d1)
{
return charAtPos(k, dfpos[k][1]) - charAtPos(k+1, dfpos[k][1]);
}
if ( (dfpos[k][0]<d1) || (charAtPos(k, d1+1) == charAtPos(k+1, d2+1)) )
{
return charAtPos(k, dfpos[k][0]) - charAtPos(k+1, dfpos[k][0]);
}
return charAtPos(k, d1+1) - charAtPos(k+1, d2+1);
}
int k1 = k;
int k2 = k+1;
int z = 1;
if (d1 > d2)
{
z = d1;
d1 = d2;
d2 =z;
z = -1;
k1 = k+1;
k2 = k;
}
if (dfpos[k][0] < d1)
{
return z*(charAtPos(k1, dfpos[k][0]) - charAtPos(k2, dfpos[k][0]));
}
if (d1 < dfpos[k][0])
{
return z*(charAtPos(k1, d1+1) - charAtPos(k2, d1));
}
int p1 = d1+1;
int p2 = d1;
while (charAtPos(k1, p1)==charAtPos(k2,p2))
{
if (p1>= words[k1].length() && p2>= words[k2].length() )
{
return 0;
}
p1++;
p2++;
if (p2==d2)
{
p2++;
}
}
return z*(charAtPos(k1, p1) - charAtPos(k2,p2));
}
public Object solve() {
int i,j,N = readInt();
words = new String[N];
for (i=0; i<N; i++)
{
words[i] = readLn();
}
D_cnt = new int[N];
D = new int[N][];
U = new int[N][];
for (i=0; i<N; i++)
{
get_d_list(words[i], i);
}
dfpos = new int[N][2];
for (i=0; i+1<N; i++)
{
dfpos[i][0] = -1;
dfpos[i][1] = -1;
j = 0;
while ( (j<words[i].length()) || (j<words[i+1].length()) )
{
if (charAtPos(i,j) != charAtPos(i+1,j))
{
if (dfpos[i][0] == -1)
{
dfpos[i][0] = j;
}
else
{
dfpos[i][1] = j;
break;
}
}
j ++;
}
}
int[][] next = new int[N-1][];
int p;
for (i=0; i<N-1; i++)
{
next[i] = new int[D_cnt[i]];
p = 0;
for (j=0; j<D_cnt[i]; j++)
{
while ( (p<D_cnt[i+1]) && (cmp(i, D[i][j], D[i+1][p])>0) )
{
p ++;
}
next[i][j] = p;
}
}
long[][] R = new long[N][];
long M = 1000000007;
R[N-1] = new long[ D_cnt[N-1]+1 ];
R[N-1][D_cnt[N-1]] = 0;
for (i=D_cnt[N-1]-1; i>=0; i--)
{
R[N-1][i] = (R[N-1][i+1] + U[N-1][i]) % M;
}
for (i=N-2; i>=0; i--)
{
R[i] = new long[ D_cnt[i]+1 ];
R[i][D_cnt[i]] = 0;
for (j=D_cnt[i]-1; j>=0; j--)
{
R[i][j] = (R[i][j+1] + U[i][j] * R[i+1][next[i][j]]) % M;
}
}
return R[0][0];
//return strf("%f", 0);
//out.printf("Case #%d: \n", caseNumber);
//return null;
}
public int caseNumber;
TestCase(int number) {
caseNumber = number;
}
public void run(){
Object r = this.solve();
if ((r != null))
{
//outputCaseNumber(r);
out.println(r);
}
}
public String impossible(){
return "IMPOSSIBLE";
}
public String strf(String format, Object... args)
{
return String.format(format, args);
}
// public void outputCaseNumber(Object r){
// //out.printf("Case #%d:", caseNumber);
// if (r != null)
// {
// // out.print(" ");
// out.print(r);
// }
// out.print("\n");
// }
}
public void run() {
//while (true)
{
int t = multiply_tests ? readInt() : 1;
for (int i = 0; i < t; i++) {
TestCase T = new TestCase(i + 1);
T.run();
}
}
}
public Main(BufferedReader _in, PrintStream _out){
in = _in;
out = _out;
}
public static void main(String args[]) {
Locale.setDefault(Locale.US);
Main S;
try {
S = new Main(
new BufferedReader(new InputStreamReader(System.in)),
System.out
);
} catch (Exception e) {
return;
}
S.run();
}
private StringTokenizer tokenizer = null;
public int readInt() {
return Integer.parseInt(readToken());
}
public long readLong() {
return Long.parseLong(readToken());
}
public double readDouble() {
return Double.parseDouble(readToken());
}
public String readLn() {
try {
String s;
while ((s = in.readLine()).length() == 0);
return s;
} catch (Exception e) {
return "";
}
}
public String readToken() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (Exception e) {
return "";
}
}
public int[] readIntArray(int n) {
int[] x = new int[n];
readIntArray(x, n);
return x;
}
public int[] readIntArrayBuf(int n) {
int[] x = new int[n];
readIntArrayBuf(x, n);
return x;
}
public void readIntArray(int[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readInt();
}
}
public long[] readLongArray(int n) {
long[] x = new long[n];
readLongArray(x, n);
return x;
}
public long[] readLongArrayBuf(int n) {
long[] x = new long[n];
readLongArrayBuf(x, n);
return x;
}
public void readLongArray(long[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readLong();
}
}
public void logWrite(String format, Object... args) {
if (!log_enabled) {
return;
}
out.printf(format, args);
}
public void readLongArrayBuf(long[] x, int n) {
char[]buf = new char[1000000];
long r = -1;
int k= 0, l = 0;
long d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void readIntArrayBuf(int[] x, int n) {
char[]buf = new char[1000000];
int r = -1;
int k= 0, l = 0;
int d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void printArray(long[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(int[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(long[] a, int n, char dl)
{
long x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printArray(int[] a, int n, char dl)
{
int x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printMatrix(int[][] a, int n, int m)
{
int x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
public void printMatrix(long[][] a, int n, int m)
{
long x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
}
|
Java
|
["3\nabcd\nzaza\nataka", "4\ndfs\nbfs\nsms\nmms", "3\nabc\nbcd\na", "6\nlapochka\nkartyshka\nbigbabytape\nmorgenshtern\nssshhhiiittt\nqueen"]
|
1.5 seconds
|
["4", "8", "0", "2028"]
|
NoteNotice that the elders could have written an empty word (but they surely cast a spell on it so it holds a length $$$1$$$ now).
|
Java 8
|
standard input
|
[
"dp",
"hashing",
"string suffix structures",
"implementation",
"strings"
] |
b27f6ae6fbad129758bba893f20b6df9
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of words in the scroll. The $$$i$$$-th of the next $$$n$$$ lines contains a string consisting of lowercase English letters: the $$$i$$$-th word in the scroll. The length of each word is more or equal than $$$1$$$. The sum of lengths of words does not exceed $$$20000$$$.
| 2,800
|
Print one integer: the number of ways to get a version of the original from the scroll modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
bdc8ce1029b4904c2221054b4d1c22cf
|
train_001.jsonl
|
1596810900
|
This is an easier version of the problem E with smaller constraints.Twilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin.To hide the crucial information from evil eyes, pony elders cast a spell on the scroll. That spell adds exactly one letter in any place to each word it is cast on. To make the path to the knowledge more tangled elders chose some of words in the scroll and cast a spell on them.Twilight Sparkle knows that the elders admired the order in all things so the scroll original scroll contained words in lexicographically non-decreasing order. She is asked to delete one letter from some of the words of the scroll (to undo the spell) to get some version of the original scroll. Unfortunately, there may be more than one way to recover the ancient scroll. To not let the important knowledge slip by Twilight has to look through all variants of the original scroll and find the required one. To estimate the maximum time Twilight may spend on the work she needs to know the number of variants she has to look through. She asks you to find that number! Since that number can be very big, Twilight asks you to find it modulo $$$10^9+7$$$.It may occur that princess Celestia has sent a wrong scroll so the answer may not exist.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
|
256 megabytes
|
import java.io.*;
import java.lang.Math;
import java.util.*;
public class Main {
public BufferedReader in;
public PrintStream out;
public boolean log_enabled = false;
public boolean multiply_tests = false;
public static boolean do_gen_test = false;
public void gen_test() {
int i,j,k = 7;
int r, cnt = 0;
for (i=1; i<=k; i++)
{
r = 1;
for (j=0; j<i; j++)
{
r *= 3;
}
cnt += r;
}
String[] list = new String[cnt];
String w;
int u, x, c = 0;
for (i=1; i<=k; i++)
{
r = 1;
for (j=0; j<i; j++)
{
r *= 3;
}
for (u=0; u<r; u++)
{
w = "";
x = u;
for (j=0; j<i; j++)
{
w = w.concat( String.valueOf((char)( x % 3 + 'a' )) );
x /= 3;
}
list[c++] = w;
}
}
out.println(2*cnt*cnt);
for (i=0; i<cnt; i++)
{
for (j=0; j<cnt; j++)
{
out.println(list[i]);
out.println(list[j]);
}
}
}
public int N;
public int[][] D;
public int[][] U;
public int[] D_cnt;
public String[] words;
public int [][] dfpos;
private class TestCase {
public int charAtPos(int k, int j)
{
return (j>=0) && (j<words[k].length()) ? (int)words[k].charAt(j) : 0;
}
public void get_d_list(String s, int k)
{
int i, cnt = 2, n = s.length();
for (i=1; i<n; i++)
{
if (s.charAt(i)!=s.charAt(i-1))
{
cnt ++;
}
}
D_cnt[k] = cnt;
D[k] = new int[cnt];
U[k] = new int[cnt];
int l = 0, r = cnt-1;
int u = 1;
for (i=0; i<n; i++)
{
if ((i+1<n)&&(s.charAt(i)==s.charAt(i+1)))
{
u++;
continue;
}
if ((i+1 == n) || s.charAt(i+1) < s.charAt(i))
{
U[k][l] = u;
D[k][l++] = i;
}
else
{
U[k][r] = u;
D[k][r--] = i;
}
u = 1;
}
D[k][l] = n;
U[k][l] = 1;
}
public int _cmp(int k, int d1, int d2)
{
String w1 = words[k];
if (d1<w1.length())
{
w1 = w1.substring(0, d1).concat(
w1.substring(d1+1)
);
}
String w2 = words[k+1];
if (d2<w2.length())
{
w2 = w2.substring(0, d2).concat(
w2.substring(d2+1)
);
}
int c1 = _cmp(k, d1, d2);
//c = _cmp(k, d1, d2);
int c2 = w1.compareTo(w2);
if ((c1*c2<0)|| (c1*c1+c2*c2 == 1) )
{
int c3 = _cmp(k, d1, d2);
}
return w1.compareTo(w2);
}
public int cmp(int k, int d1, int d2)
{
if (d1==d2)
{
if (dfpos[k][0]==d1)
{
return charAtPos(k, dfpos[k][1]) - charAtPos(k+1, dfpos[k][1]);
}
if ( (dfpos[k][0]<d1) || (charAtPos(k, d1+1) == charAtPos(k+1, d2+1)) )
{
return charAtPos(k, dfpos[k][0]) - charAtPos(k+1, dfpos[k][0]);
}
return charAtPos(k, d1+1) - charAtPos(k+1, d2+1);
}
int k1 = k;
int k2 = k+1;
int z = 1;
if (d1 > d2)
{
z = d1;
d1 = d2;
d2 =z;
z = -1;
k1 = k+1;
k2 = k;
}
if ( (dfpos[k][0]>=0) && (dfpos[k][0] < d1))
{
return z*(charAtPos(k1, dfpos[k][0]) - charAtPos(k2, dfpos[k][0]));
}
if ((dfpos[k][0]==-1) || (d1 < dfpos[k][0]))
{
return z*(charAtPos(k1, d1+1) - charAtPos(k2, d1));
}
int p1 = d1+1;
int p2 = d1;
while (charAtPos(k1, p1)==charAtPos(k2,p2))
{
if (p1>= words[k1].length() && p2>= words[k2].length() )
{
return 0;
}
p1++;
p2++;
if (p2==d2)
{
p2++;
}
}
return z*(charAtPos(k1, p1) - charAtPos(k2,p2));
}
public Object solve() {
int i,j,N = readInt();
words = new String[N];
for (i=0; i<N; i++)
{
words[i] = readLn();
}
D_cnt = new int[N];
D = new int[N][];
U = new int[N][];
for (i=0; i<N; i++)
{
get_d_list(words[i], i);
}
dfpos = new int[N][2];
for (i=0; i+1<N; i++)
{
dfpos[i][0] = -1;
dfpos[i][1] = -1;
j = 0;
while ( (j<words[i].length()) || (j<words[i+1].length()) )
{
if (charAtPos(i,j) != charAtPos(i+1,j))
{
if (dfpos[i][0] == -1)
{
dfpos[i][0] = j;
}
else
{
dfpos[i][1] = j;
break;
}
}
j ++;
}
}
int[][] next = new int[N-1][];
int p;
for (i=0; i<N-1; i++)
{
next[i] = new int[D_cnt[i]];
p = 0;
for (j=0; j<D_cnt[i]; j++)
{
while ( (p<D_cnt[i+1]) && (cmp(i, D[i][j], D[i+1][p])>0) )
{
p ++;
}
next[i][j] = p;
}
}
long[][] R = new long[N][];
long M = 1000000007;
R[N-1] = new long[ D_cnt[N-1]+1 ];
R[N-1][D_cnt[N-1]] = 0;
for (i=D_cnt[N-1]-1; i>=0; i--)
{
R[N-1][i] = (R[N-1][i+1] + U[N-1][i]) % M;
}
for (i=N-2; i>=0; i--)
{
R[i] = new long[ D_cnt[i]+1 ];
R[i][D_cnt[i]] = 0;
for (j=D_cnt[i]-1; j>=0; j--)
{
R[i][j] = (R[i][j+1] + U[i][j] * R[i+1][next[i][j]]) % M;
}
}
return R[0][0];
//return strf("%f", 0);
//out.printf("Case #%d: \n", caseNumber);
//return null;
}
public int caseNumber;
TestCase(int number) {
caseNumber = number;
}
public void run(){
Object r = this.solve();
if ((r != null))
{
//outputCaseNumber(r);
out.println(r);
}
}
public String impossible(){
return "IMPOSSIBLE";
}
public String strf(String format, Object... args)
{
return String.format(format, args);
}
// public void outputCaseNumber(Object r){
// //out.printf("Case #%d:", caseNumber);
// if (r != null)
// {
// // out.print(" ");
// out.print(r);
// }
// out.print("\n");
// }
}
public void run() {
//while (true)
{
int t = multiply_tests ? readInt() : 1;
for (int i = 0; i < t; i++) {
TestCase T = new TestCase(i + 1);
T.run();
}
}
}
public Main(BufferedReader _in, PrintStream _out){
in = _in;
out = _out;
}
public static void main(String args[]) {
Locale.setDefault(Locale.US);
Main S;
try {
S = new Main(
new BufferedReader(new InputStreamReader(System.in)),
System.out
);
} catch (Exception e) {
return;
}
S.run();
}
private StringTokenizer tokenizer = null;
public int readInt() {
return Integer.parseInt(readToken());
}
public long readLong() {
return Long.parseLong(readToken());
}
public double readDouble() {
return Double.parseDouble(readToken());
}
public String readLn() {
try {
String s;
while ((s = in.readLine()).length() == 0);
return s;
} catch (Exception e) {
return "";
}
}
public String readToken() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (Exception e) {
return "";
}
}
public int[] readIntArray(int n) {
int[] x = new int[n];
readIntArray(x, n);
return x;
}
public int[] readIntArrayBuf(int n) {
int[] x = new int[n];
readIntArrayBuf(x, n);
return x;
}
public void readIntArray(int[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readInt();
}
}
public long[] readLongArray(int n) {
long[] x = new long[n];
readLongArray(x, n);
return x;
}
public long[] readLongArrayBuf(int n) {
long[] x = new long[n];
readLongArrayBuf(x, n);
return x;
}
public void readLongArray(long[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readLong();
}
}
public void logWrite(String format, Object... args) {
if (!log_enabled) {
return;
}
out.printf(format, args);
}
public void readLongArrayBuf(long[] x, int n) {
char[]buf = new char[1000000];
long r = -1;
int k= 0, l = 0;
long d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void readIntArrayBuf(int[] x, int n) {
char[]buf = new char[1000000];
int r = -1;
int k= 0, l = 0;
int d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void printArray(long[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(int[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(long[] a, int n, char dl)
{
long x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printArray(int[] a, int n, char dl)
{
int x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printMatrix(int[][] a, int n, int m)
{
int x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
public void printMatrix(long[][] a, int n, int m)
{
long x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
}
|
Java
|
["3\nabcd\nzaza\nataka", "4\ndfs\nbfs\nsms\nmms", "3\nabc\nbcd\na", "6\nlapochka\nkartyshka\nbigbabytape\nmorgenshtern\nssshhhiiittt\nqueen"]
|
1.5 seconds
|
["4", "8", "0", "2028"]
|
NoteNotice that the elders could have written an empty word (but they surely cast a spell on it so it holds a length $$$1$$$ now).
|
Java 8
|
standard input
|
[
"dp",
"hashing",
"string suffix structures",
"implementation",
"strings"
] |
b27f6ae6fbad129758bba893f20b6df9
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of words in the scroll. The $$$i$$$-th of the next $$$n$$$ lines contains a string consisting of lowercase English letters: the $$$i$$$-th word in the scroll. The length of each word is more or equal than $$$1$$$. The sum of lengths of words does not exceed $$$20000$$$.
| 2,800
|
Print one integer: the number of ways to get a version of the original from the scroll modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
c52090b7ec963d4ce63f993c9ea850ca
|
train_001.jsonl
|
1520583000
|
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
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);
A949 solver = new A949();
solver.solve(1, in, out);
out.close();
}
static class A949 {
int N;
char[] num;
TreeSet<Integer> zero;
TreeSet<Integer> one;
public void solve(int testNumber, FastScanner s, PrintWriter out) {
zero = new TreeSet<>();
one = new TreeSet<>();
num = s.next().toCharArray();
N = num.length;
for (int i = 0; i < N; i++)
if (num[i] == '0')
zero.add(i + 1);
else
one.add(i + 1);
int K = 0;
StringBuilder oo = new StringBuilder();
while (!one.isEmpty()) {
if (zero.isEmpty()) {
out.println(-1);
return;
}
K++;
int cur = zero.pollFirst();
N = 1;
boolean p1 = true;
StringBuilder line = new StringBuilder();
line.append(cur);
while (true) {
if (p1)
if (one.isEmpty() || one.higher(cur) == null) {
break;
} else {
int nxt = one.higher(cur);
one.remove(nxt);
line.append(" " + nxt);
cur = nxt;
N++;
}
else {
if (zero.isEmpty() || zero.higher(cur) == null) {
out.println(-1);
return;
} else {
int nxt = zero.higher(cur);
zero.remove(nxt);
line.append(" " + nxt);
cur = nxt;
N++;
}
}
p1 = !p1;
}
oo.append(N + " ");
oo.append(line + "\n");
}
while (!zero.isEmpty()) {
oo.append("1 " + zero.pollFirst() + "\n");
K++;
}
out.println(K);
out.print(oo.toString());
}
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
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++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
}
}
|
Java
|
["0010100", "111"]
|
1 second
|
["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"]
| null |
Java 8
|
standard input
|
[
"greedy"
] |
37b34461876af7f2e845417268b55ffa
|
In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200β000 characters.
| 1,600
|
If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1ββ€βkββ€β|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1ββ€βliββ€β|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.
|
standard output
| |
PASSED
|
a3ebb5c8b6b0ebf4372e4739d425cc81
|
train_001.jsonl
|
1520583000
|
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
|
512 megabytes
|
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class A {
FastScanner scanner;
PrintWriter writer;
void solve() throws IOException {
scanner = new FastScanner(System.in);
writer = new PrintWriter(System.out);
String s = scanner.nextLine().trim();
List<List<Integer>> zebras = findZebras(s);
if (zebras == null) {
writer.println(-1);
} else {
writer.println(zebras.size());
for (List<Integer> z : zebras) {
writer.print(z.size());
for (int x : z) {
writer.print(" " + (x + 1));
}
writer.println();
}
}
writer.close();
}
List<List<Integer>> findZebras(String s) {
List<List<Integer>> bs = new ArrayList<>();
List<List<Integer>> gs = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '0') {
List<Integer> b;
if (!gs.isEmpty()) {
b = gs.get(gs.size() - 1);
gs.remove(gs.size() - 1);
} else {
b = new ArrayList<>();
}
b.add(i);
bs.add(b);
} else {
if (!bs.isEmpty()) {
List<Integer> g = bs.get(bs.size() - 1);
bs.remove(bs.size() - 1);
g.add(i);
gs.add(g);
} else {
return null;
}
}
}
if (!gs.isEmpty())
return null;
return bs;
}
public static void main(String... args) throws IOException {
new A().solve();
}
static class FastScanner {
BufferedReader br;
StringTokenizer tokenizer;
FastScanner(String fileName) throws FileNotFoundException {
this(new FileInputStream(new File(fileName)));
}
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String nextLine() throws IOException {
tokenizer = null;
return br.readLine();
}
String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
|
Java
|
["0010100", "111"]
|
1 second
|
["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"]
| null |
Java 8
|
standard input
|
[
"greedy"
] |
37b34461876af7f2e845417268b55ffa
|
In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200β000 characters.
| 1,600
|
If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1ββ€βkββ€β|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1ββ€βliββ€β|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.
|
standard output
| |
PASSED
|
f4d52b88cb9ac7eddf5060c198ff3bb3
|
train_001.jsonl
|
1520583000
|
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
char[] s = sc.next().toCharArray();
ArrayList<ArrayList<Integer>> tZero = new ArrayList<>();
ArrayList<ArrayList<Integer>> tOne = new ArrayList<>();
boolean good = true;
int idx = 1;
for(char c: s) if(c == '0') {
ArrayList<Integer> arr = tOne.isEmpty() ? new ArrayList<>(1) : tOne.remove(tOne.size() - 1);
arr.add(idx++);
tZero.add(arr);
} else {
if(tZero.isEmpty()) {
good = false;
break;
}
ArrayList<Integer> arr = tZero.remove(tZero.size() - 1);
arr.add(idx++);
tOne.add(arr);
}
if(!tOne.isEmpty())
good = false;
if(!good)
out.println(-1);
else {
out.println(tZero.size());
for(ArrayList<Integer> arr: tZero) {
out.print(arr.size());
for(int x: arr)
out.print(" " + x);
out.println();
}
}
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
}
}
|
Java
|
["0010100", "111"]
|
1 second
|
["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"]
| null |
Java 8
|
standard input
|
[
"greedy"
] |
37b34461876af7f2e845417268b55ffa
|
In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200β000 characters.
| 1,600
|
If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1ββ€βkββ€β|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1ββ€βliββ€β|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.
|
standard output
| |
PASSED
|
a18b3373dd3bcc7254903f6f76d440ee
|
train_001.jsonl
|
1520583000
|
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.LinkedList;
public class ZebrasA469 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
String s=in.readLine();
LinkedList<Integer>[] lls=new LinkedList[s.length()];
int c=0;
LinkedList<Integer> zs=new LinkedList<Integer>(), os=new LinkedList<Integer>();
int t;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='0') {
if(os.size()==0) {
lls[c]=new LinkedList<Integer>();
lls[c].add(i+1);
zs.add(c);
c++;
}
else {
t=os.removeFirst();
lls[t].add(i+1);
zs.add(t);
}
}
else {
if(zs.size()==0) {
out.println("-1");
out.close();
return;
}
t=zs.removeFirst();
lls[t].add(i+1);
os.add(t);
}
}
if(os.size()==0) {
out.println(c);
for(int i=0;i<c;i++) {
out.print(lls[i].size());
out.print(" ");
for(Integer k: lls[i]) {
out.print(k);
out.print(" ");
}
out.println();
}
}
else {
out.println("-1");
}
in.close();
out.close();
}
}
|
Java
|
["0010100", "111"]
|
1 second
|
["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"]
| null |
Java 8
|
standard input
|
[
"greedy"
] |
37b34461876af7f2e845417268b55ffa
|
In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200β000 characters.
| 1,600
|
If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1ββ€βkββ€β|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1ββ€βliββ€β|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.
|
standard output
| |
PASSED
|
2ef940b06d74875bda56a0ecac9c6152
|
train_001.jsonl
|
1520583000
|
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class MainA {
static final StdIn in = new StdIn();
static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
char[] s = in.next().toCharArray();
int n=s.length;
//if(s[0]=='1')
// fk();
List<Integer> s0 = new ArrayList<Integer>(), s1 = new ArrayList<Integer>();
int[] p = new int[n];
Arrays.fill(p, -1);
for(int i=0; i<n; ++i) {
if(s[i]=='0') {
if(!s1.isEmpty()) {
p[i]=s1.get(s1.size()-1);
s1.remove(s1.size()-1);
}
s0.add(i);
} else {
if(s0.isEmpty())
fk();
p[i]=s0.get(s0.size()-1);
s0.remove(s0.size()-1);
s1.add(i);
}
}
if(!s1.isEmpty())
fk();
out.println(s0.size());
for(int i=0; i<s0.size(); ++i) {
List<Integer> ps = new ArrayList<Integer>();
for(int j=s0.get(i); j!=-1; j=p[j])
ps.add(j);
out.print(ps.size());
for(int j=ps.size()-1; j>=0; --j)
out.print(" "+(ps.get(j)+1));
out.println();
}
out.close();
}
static void fk() {
System.out.println(-1);
System.exit(0);
}
static class StdIn {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try{
din = new DataInputStream(in);
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
s.append((char)c);
c=read();
}
return s.toString();
}
public String nextLine() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
s.append((char)c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n, int os) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt()+os;
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n, long os) {
long[] ar = new long[n];
for(int i=0; i<n; ++i)
ar[i]=nextLong()+os;
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
|
Java
|
["0010100", "111"]
|
1 second
|
["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"]
| null |
Java 8
|
standard input
|
[
"greedy"
] |
37b34461876af7f2e845417268b55ffa
|
In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200β000 characters.
| 1,600
|
If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1ββ€βkββ€β|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1ββ€βliββ€β|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.
|
standard output
| |
PASSED
|
7c9178cb572c89d1a9dd515e69a7e17e
|
train_001.jsonl
|
1520583000
|
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.StringTokenizer;
public class CF {
private FastScanner in;
private PrintWriter out;
void solve() {
String input = in.next();
Deque<List<Integer>> zeroTerminatedBlocks = new ArrayDeque<>();
Deque<List<Integer>> oneTerminatedBlocks = new ArrayDeque<>();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '0') {
if (oneTerminatedBlocks.size() > 0) {
List<Integer> positions = oneTerminatedBlocks.poll();
positions.add(i + 1);
zeroTerminatedBlocks.add(positions);
} else {
List<Integer> newList = new ArrayList<>();
newList.add(i+1);
zeroTerminatedBlocks.add(newList);
}
} else {
if (zeroTerminatedBlocks.isEmpty()) {
out.println(-1);
return;
} else {
List<Integer> positions = zeroTerminatedBlocks.poll();
positions.add(i + 1);
oneTerminatedBlocks.add(positions);
}
}
}
if (oneTerminatedBlocks.size() > 0) {
out.println(-1);
} else {
out.println(zeroTerminatedBlocks.size());
for (List<Integer> zebra : zeroTerminatedBlocks) {
out.print(zebra.size());
for (Integer pos : zebra) {
out.print(' ');
out.print(pos);
}
out.println();
}
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void run() {
try {
in = new FastScanner(new File("test.in"));
out = new PrintWriter(new File("test.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new CF().runIO();
}
}
|
Java
|
["0010100", "111"]
|
1 second
|
["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"]
| null |
Java 8
|
standard input
|
[
"greedy"
] |
37b34461876af7f2e845417268b55ffa
|
In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200β000 characters.
| 1,600
|
If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1ββ€βkββ€β|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1ββ€βliββ€β|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.
|
standard output
| |
PASSED
|
e4ff933394798379e7818581d584ee74
|
train_001.jsonl
|
1520583000
|
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
|
512 megabytes
|
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Scanner;
public class a949 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] s = in.nextLine().toCharArray();
PrintWriter out = new PrintWriter(System.out);
int curZero = -1;
int curOne = -1;
ArrayDeque<Integer> justZero = new ArrayDeque<Integer>(s.length);
ArrayDeque<Integer>[] zeroEnding = new ArrayDeque[s.length / 3 + 1];
ArrayDeque<Integer>[] oneEnding = new ArrayDeque[s.length / 2 + 1];
for (int i = 0; i < s.length; i++) {
if (s[i] == '0') {
if (curOne > -1) {
ArrayDeque<Integer> next;
next = oneEnding[curOne--];
next.add(i);
zeroEnding[++curZero] = next;
} else {
justZero.addLast(i);
}
} else if (curZero > -1) {
ArrayDeque<Integer> here = zeroEnding[curZero--];
here.add(i);
oneEnding[++curOne] = here;
} else if (justZero.size() > 0) {
ArrayDeque<Integer> here = new ArrayDeque<Integer>();
here.add(justZero.pollLast());
here.add(i);
oneEnding[++curOne] = here;
} else {
out.println(-1);
out.close();
return;
}
}
if (curOne > -1) {
out.println(-1);
} else {
out.println(curZero + 1 + justZero.size());
for (int i = 0; i <= curZero; i++) {
out.print(zeroEnding[i].size());
for (Integer integer : zeroEnding[i]) {
out.printf(" %d", integer + 1);
}
out.println();
}
for (int z : justZero) {
out.printf("1 %d\n", z + 1);
}
}
out.close();
}
}
|
Java
|
["0010100", "111"]
|
1 second
|
["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"]
| null |
Java 8
|
standard input
|
[
"greedy"
] |
37b34461876af7f2e845417268b55ffa
|
In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200β000 characters.
| 1,600
|
If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1ββ€βkββ€β|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1ββ€βliββ€β|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.