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
|
8227f56664b5a59e4d79a297c01a3728
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class B {
private static int[] games = new int[1];
private static int[] sum1 = new int[1];
private static int[] sum2 = new int[1];
static int N;
private static class pair implements Comparable<pair>{
int s; int t;
public int compareTo(pair arg0) {
int a = Double.compare(s, arg0.s);
if(a!=0)return a;
return Double.compare(t, arg0.t);
}
public pair(int a, int b){
s=a;t=b;
}
public String toString(){
return s + " " + t;
}
}
public static void main(String[] args) throws IOException {
// System.out.println((int)'1');//49
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(f.readLine());
games = new int[N+1];
sum1 = new int[N+1];
sum2 = new int[N+1];//1-based indexing
for(int i=1;i<=N;i++){
int t = f.read();
games[i] = t - 48;
f.read();
}
int winner = (games[N] == 1 ? 1 : 2);
int loser = (games[N] == 2 ? 1 : 2);
for(int i=1;i<=N;i++){
sum1[i] = sum1[i-1] + (games[i] == winner ? 1 : 0);
sum2[i] = sum2[i-1] + (games[i] == loser ? 1 : 0);
}//WLOG, 1 is the winner.
HashSet<Integer> tvals = new HashSet<Integer>();//eliminates duplicates automatically
for(int i=N;i>=1;i--){
if(sum1[N] - sum1[i-1] > sum2[N] - sum2[i-1]){
tvals.add(sum1[N] - sum1[i-1]);
}
}
// System.out.println(tvals);
ArrayList<pair> ans = new ArrayList<pair>();
for(int t : tvals){
int s = works(t);
if(s != -1){
ans.add(new pair(s,t));
}
}
Collections.sort(ans);
System.out.println(ans.size());
for(pair p : ans){
System.out.println(p);
}
}
private static int works(int t) {
int win = 0;
int lose = 0;
int endLast = 0;
while(endLast != N){
int lo = endLast;
int hi = Math.min(endLast + 2 * t - 1, N);
while(hi - lo > 1){
int mid = (hi + lo) / 2;
int x = sum1[mid] - sum1[endLast];
int y = sum2[mid] - sum2[endLast];
if(x < t && y < t){
lo = mid;
}
else{
hi = mid;
}
}
if(sum1[hi] - sum1[endLast] == t){
win++;
}
else if(sum2[hi] - sum2[endLast] == t){
lose++;
}
else{
return -1;
}
endLast = hi;
}
if(win > lose){
return win;
}
return -1;
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
654b07caa2fe8f131281ea272374570d
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nipuna Samarasekara
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
// 689^*(
static int[][] par1,par2;
static int[] a;
static int type,n;
public void solve(int testNumber, FastScanner in, FastPrinter out) {
n=in.nextInt();
a=in.readIntArray(n);
par1= new int[20][n];
par2= new int[20][n];
type=a[n-1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 20; j++) {
par1[j][i]=n;
par2[j][i]=n;
}
}
int pp1=n,pp2=n;
for (int i = n-1; i >=0 ; i--) {
par1[0][i]=pp1;
par2[0][i]=pp2;
if (a[i]==type)pp1=i;
else pp2=i;
}
for (int i = 1; i < 20 ; i++) {
for (int j = 0; j < n; j++) {
if (par1[i-1][j]!=n)
par1[i][j]=par1[i-1][par1[i-1][j]];
if (par2[i-1][j]!=n)
par2[i][j]=par2[i-1][par2[i-1][j]];
}
}
int ctt=0;
ArrayList<P> ans= new ArrayList<P>();
int wscore=0,lscore=0;
int pws=-1 ;
for (int i = n-1; i >=0; i--) {
if (a[i]==type)wscore++;
else lscore++;
if (wscore>lscore&&pws!=wscore){
pws=wscore;
// System.out.println("dd" +wscore);
int setSize=wscore;
int st=0;
int wsets=0,lsets=0;
while (st<n){
int p1=getp1(st, setSize);
int p2=getp2(st, setSize);
int min=Math.min(p1,p2);
// System.out.println(p1+" p1 p2 "+p2);
// System.out.println(st+ " st min " +min);
if (min<n){
if (min==p1)wsets++;
else lsets++;
}
st=min+1;
}
if (st==n&&wsets>lsets){
ctt++;
P p= new P();
p.s=wsets;
p.t=setSize;
ans.add(p);
}
}
}
Collections.sort(ans);
out.println(ctt);
for (int i = 0; i < ctt; i++) {
out.println(ans.get(i).s+" "+ans.get(i).t);
}
}
static int getp1(int st,int ct){
// System.out.println(st+" t1 "+ct);
int t=type;
int pos=st,ctt=ct;
if (a[pos]==t)ctt--;
// while (ctt>0&&pos<n){
// pos++;
// if (pos==n)break;
// if (a[pos]==t)ctt--;
//
//
// }
if (ctt==0)return pos;
int pow=0;
int cttc=ctt;
while (cttc>1){
pow++;
cttc/=2;
}
pos=par1[pow][pos];
if (pos==n)return pos;
// System.out.println(pow+" ctt "+ctt);
return getp1(pos, (int) (ctt-Math.pow(2,pow)+1));
};
static int getp2(int st,int ct){
// System.out.println(st+" t2 "+ct);
int t=3-type;
int pos=st,ctt=ct;
if (a[pos]==t)ctt--;
// while (ctt>0&&pos<n){
// pos++;
// if (pos==n)break;
// if (a[pos]==t)ctt--;
//
//
// }
if (ctt==0)return pos;
int pow=0;
int cttc=ctt;
while (cttc>1){
pow++;
cttc/=2;
}
pos=par2[pow][pos];
if (pos==n)return pos;
return getp2(pos, (int) (ctt - Math.pow(2, pow) + 1));
};
class P implements Comparable<P>{
int s,t;
public int compareTo(P o) {
if (this.s!=o.s)return this.s-o.s;
else
return this.t-o.t; //To change body of implemented methods use File | Settings | File Templates.
}
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
9a5287fa1824309dceff0929b7736665
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
public class C283_B {
public static void main(String []args) {
new Solution().solve();
}
}
class Solution {
FastReader fr = new FastReader();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public void solve() {
int n = fr.nextInt();
int []data = new int[n];
int [][]p = new int[n+1][2];
int [][]result = new int[n][2];
int resultCount = 0;
int prevA = 0, prevB = 0;
for (int i = 0; i < n; i++) {
data[i] = fr.nextInt();
if (data[i] == 1) {
p[i+1][0] = ++prevA;
p[i+1][1] = prevB;
} else {
p[i+1][0] = prevA;
p[i+1][1] = ++prevB;
}
}
for (int i = 1; i <= n; i++) {
boolean endLoop = false;
int start = 0;
int setAWon = 0, setBWon = 0;
while (!endLoop) {
int prevEnd = -1;
int end = Math.min(start + i*2, n);
while (start < end) {
if (p[end][0] - p[start][0] == i && p[end][0] != p[end - 1][0] && p[end][1] - p[start][1] < i) {
setAWon++;
if (end == n) {
if (setAWon > setBWon) {
result[resultCount][0] = setAWon;
result[resultCount][1] = i;
resultCount++;
} else {
endLoop = true;
}
}
start = end;
}
if (p[end][1] - p[start][1] == i && p[end][1] != p[end - 1][1] && p[end][0] - p[start][0] < i) {
setBWon++;
if (end == n) {
if (setBWon > setAWon) {
result[resultCount][0] = setBWon;
result[resultCount][1] = i;
resultCount++;
} else {
endLoop = true;
}
}
start = end;
}
if (end == n && p[end][1] - p[start][1] < i && p[end][0] - p[start][0] < i) {
endLoop = true;
break;
}
if (start == end) {
break;
}
int middle = (start + end) / 2;
if (prevEnd > 0) {
middle = (end + prevEnd) / 2;
}
while (p[middle][1] - p[start][1] < i && p[middle][0] - p[start][0] < i) {
prevEnd = middle;
middle = (end + prevEnd) / 2;
}
end = middle;
}
}
}
System.out.println(resultCount);
int [][]r = Arrays.copyOfRange(result, 0, resultCount);
Arrays.sort(r, new Comparator<int[]>() {
@Override
public int compare(int[] ints, int[] t1) {
if (ints[0] == t1[0]) {
return Integer.compare(ints[1], t1[1]);
} else {
return Integer.compare(ints[0], t1[0]);
}
}
});
for (int i = 0; i < resultCount; i++) {
System.out.println(r[i][0] + " " + r[i][1]);
}
}
}
class FastReader {
private InputStream is = new BufferedInputStream(System.in);
private int bufferSize = 1 << 17;
private byte []buffer = new byte[bufferSize];
private int currentIndex = 0;
private int lastIndex = 0;
public int nextInt() {
int result = 0;
int minus = 1;
byte character = readNext();
while (character == ' ' || character == '\n' || character == '\r') {
character = readNext();
}
if (character == '-') {
minus = -1;
character = readNext();
}
while (character != ' ' && character != '\n' && character != '\r') {
result = result * 10 + (character - '0');
character = readNext();
}
return minus*result;
}
public long nextLong() {
long result = 0;
int minus = 1;
byte character = readNext();
while (character == ' ' || character == '\n' || character == '\r') {
character = readNext();
}
if (character == '-') {
minus = -1;
character = readNext();
}
while (character != ' ' && character != '\n' && character != '\r') {
result = result * 10 + (character - '0');
character = readNext();
}
return minus*result;
}
public String nextString() {
StringBuffer result = new StringBuffer();
byte character = readNext();
while (character == ' ' || character == '\n' || character == '\r') {
character = readNext();
}
while (character != ' ' && character != '\n' && character != '\r') {
result.append((char)character);
character = readNext();
}
return result.toString();
}
public String nextLine() {
StringBuffer result = new StringBuffer();
byte character = readNext();
while (character == '\n' || character == '\r') {
character = readNext();
}
while (character != '\n' && character != '\r') {
result.append((char)character);
character = readNext();
}
return result.toString();
}
private byte readNext() {
if (currentIndex == lastIndex) {
try {
lastIndex = is.read(buffer, 0, bufferSize);
} catch (IOException e) {
throw new RuntimeException("What?");
}
if (lastIndex == -1) {
buffer[0] = -1;
}
currentIndex = 0;
}
return buffer[currentIndex++];
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
51e11d712f1d04fa28630f848562f402
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int[] aSum = new int[n+1];
int[] bSum = new int[n+1];
for(int i = 1; i <= n; i++) {
aSum[i] = aSum[i-1];
bSum[i] = bSum[i-1];
if(readInt() == 1) {
aSum[i]++;
}
else {
bSum[i]++;
}
}
int[] aFirst = new int[n+1];
int[] bFirst = new int[n+1];
Arrays.fill(aFirst, Integer.MAX_VALUE);
Arrays.fill(bFirst, Integer.MAX_VALUE);
for(int i = 0; i < aSum.length; i++) {
aFirst[aSum[i]] = Math.min(aFirst[aSum[i]], i);
bFirst[bSum[i]] = Math.min(bFirst[bSum[i]], i);
}
ArrayList<State> ret = new ArrayList<State>();
for(int t = 1; t <= n; t++) {
int aWin = 0;
int bWin = 0;
int start = 0;
int lastWin = -1;
while(start < n) {
int aNeed = aSum[start] + t;
int bNeed = bSum[start] + t;
int aIndex = aNeed < aFirst.length ? aFirst[aNeed] : Integer.MAX_VALUE;
int bIndex = bNeed < bFirst.length ? bFirst[bNeed] : Integer.MAX_VALUE;
if(Math.min(aIndex, bIndex) == Integer.MAX_VALUE) {
start = Integer.MAX_VALUE;
break;
}
if(aIndex < bIndex) {
start = aIndex;
aWin++;
lastWin = 1;
}
else {
start = bIndex;
bWin++;
lastWin = 2;
}
}
if(start == n) {
if(aWin > bWin && lastWin == 1) {
ret.add(new State(aWin, t));
}
if(bWin > aWin && lastWin == 2) {
ret.add(new State(bWin, t));
}
}
}
Collections.sort(ret);
pw.println(ret.size());
for(State out: ret) {
pw.println(out);
}
}
exitImmediately();
}
static class State implements Comparable<State> {
public int x, y;
public State(int a, int b) {
x=a;
y=b;
}
public String toString() {
return x + " " + y;
}
public int compareTo(State s) {
if(x == s.x) return y - s.y;
return x - s.x;
}
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
if(!br.ready()) {
exitImmediately();
}
st = null;
return br.readLine();
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
0cefdb92abc86598cf38623b25916921
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
/*
try {
inputStream = new FileInputStream("a.in");
outputStream = new FileOutputStream("a.out");
} catch (FileNotFoundException e) {
System.err.println("File not found");
return;
}*/
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(in, out);
out.close();
}
}
class Solver {
class Ans implements Comparable<Ans>{
int s, t;
public Ans(int s, int t) {
this.s = s;
this.t = t;
}
public int compareTo(Ans o) {
if (s != o.s)
return Integer.compare(s, o.s);
return Integer.compare(t, o.t);
}
public String toString() {
return s + " " + t;
}
}
int[] a, b;
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
a = new int[n + 1];
b = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i + 1] = a[i];
b[i + 1] = b[i];
if (in.nextInt() == 1)
a[i + 1]++;
else
b[i + 1]++;
}
ArrayList<Ans> ans = new ArrayList<>();
search:
for (int t = 1; t <= n; ++t) {
int as = 0;
int bs = 0;
int st = 0;
while (st < n) {
int l = st;
int r = n + 1;
while (l < r - 1) {
int m = (l + r) / 2;
if (a[m] - a[st] >= t || b[m] - b[st] >= t)
r = m;
else
l = m;
}
if (r == n + 1)
continue search;
if (a[r] - a[st] >= t) {
as++;
if (r == n && as <= bs)
continue search;
} else {
bs++;
if (r == n && bs <= as)
continue search;
}
st = r;
}
if (as == bs)
continue;
ans.add(new Ans(Math.max(as, bs), t));
}
Collections.sort(ans);
out.println(ans.size());
for (Ans a : ans) {
out.println(a);
}
}
}
class InputReader {
private BufferedReader reader;
private 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 long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
cf87cb18874a250738464f2fc76e1175
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class ProblemB {
BufferedReader rd;
private ProblemB() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
rd.readLine();
int[] a = intarr();
int n = a.length;
int[][] p = new int[2][n+1];
for(int i=0;i<n;i++) {
p[0][i+1] = p[0][i] + (a[i]==1?1:0);
p[1][i+1] = p[1][i] + (a[i]==2?1:0);
}
NavigableMap<Integer, NavigableSet<Integer>> bys = new TreeMap<>();
int lastPlay = a[n-1]-1;
if(p[0][n] != p[1][n]) {
int winner;
if(p[0][n] > p[1][n]) {
winner = 0;
} else {
winner = 1;
}
if(winner == lastPlay) {
add(bys, Math.max(p[0][n], p[1][n]), 1);
}
}
if(p[0][n] == 0 || p[1][n] == 0) {
add(bys, 1, n);
}
boolean[] ok = new boolean[2];
for(int t=2;t<n;t++) {
int pp = 0;
int[] sets = new int[2];
int[] z = new int[2];
int last = -1;
boolean found = true;
while(pp < n) {
ok[0] = false;
ok[1] = false;
for(int j=0;j<2;j++) {
int y = p[j][pp] + t;
if(y <= p[j][n]) {
z[j] = binarySearch(p[j],pp,n,y);
ok[j] = true;
}
}
int winner;
if(ok[0]) {
if(ok[1]) {
if(z[0] < z[1]) {
winner = 0;
} else {
winner = 1;
}
} else {
winner = 0;
}
} else if(ok[1]) {
winner = 1;
} else {
found = false;
break;
}
pp = z[winner];
sets[winner]++;
last = winner;
}
if(found && last == lastPlay) {
if(sets[last] > sets[1-last]) {
add(bys, sets[last], t);
}
}
}
int res = 0;
for(Map.Entry<Integer, NavigableSet<Integer>> e: bys.entrySet()) {
res += e.getValue().size();
}
out(res);
for(Map.Entry<Integer, NavigableSet<Integer>> e: bys.entrySet()) {
Integer s = e.getKey();
for(Integer t: e.getValue()) {
out(s+" "+t);
}
}
}
private int binarySearch(int[] a, int from, int to, int k) {
int ofrom = from;
int oto = to;
while(to-from > 1) {
int mid = (from+to)/2;
if(a[mid] >= k) {
to = mid-1;
} else {
from = mid+1;
}
}
for(int j=Math.max(0,from-1);j<Math.min(a.length, to+2);j++) {
if(j >= ofrom && j <= oto) {
if(a[j] == k) {
return j;
} else if(a[j] > k) {
return -j-1;
}
}
}
return -1-(oto+1);
}
private void add(NavigableMap<Integer, NavigableSet<Integer>> bys, int s, int t) {
NavigableSet<Integer> set = bys.get(s);
if(set == null) {
set = new TreeSet<>();
bys.put(s, set);
}
set.add(t);
}
private int[] intarr() throws IOException {
return intarr(rd.readLine());
}
private int[] intarr(String s) {
String[] q = split(s);
int n = q.length;
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = Integer.parseInt(q[i]);
}
return a;
}
private String[] split(String s) {
int n = s.length();
int sp = 0;
for(int i=0;i<n;i++) {
if(s.charAt(i)==' ') {
sp++;
}
}
String[] res = new String[sp+1];
int last = 0;
int x = 0;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(c == ' ') {
res[x++] = s.substring(last,i);
last = i+1;
}
}
res[x] = s.substring(last,n);
return res;
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemB();
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
2e95f250afe03465534f420b0e37dc5e
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
while (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
int n;
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
n = nextInt();
int []a = new int[n];
int zero = 0, one = 0;
for(int i = 0; i < n; ++i) {
a[i] = nextInt() - 1;
if (a[i] == 0) ++zero;
if (a[i] == 1) ++one;
}
// if (zero == one) {
// out.println(0);
// out.close();
// return;
// }
int max = 0, s = 0;
if (one > zero) {
max = one;
s = 1;
}else {
max = zero;
s = 0;
}
int []sum1 = new int[n];
if (a[0] == s) sum1[0] = 1;
for(int i = 1; i < n; ++i) sum1[i] = sum1[i-1] + ((a[i] == s) ? 1 : 0);
int []sum2 = new int[n];
if (a[0] == 1 - s) sum2[0] = 1;
for(int i = 1; i < n; ++i) sum2[i] = sum2[i-1] + ((a[i] == 1 - s) ? 1 : 0);
// System.out.println("sum1 = " + Arrays.toString(sum1));
// System.out.println("sum2 = " + Arrays.toString(sum2));
List<P> ret = new ArrayList<P>();
for(int i = 1; i <= max; ++i) {
int sets = sets(i, sum1, sum2);
if (sets != -1) {
ret.add(new P(sets, i));
}
}
Collections.sort(ret);
out.println(ret.size());
for(P i : ret) out.println(i);
out.close();
}
public int sets(int x, int []sum1, int []sum2) {
// System.out.println("query t = " + x);
int w1 = 0, w2 = 0, last = -1;
int l = -1, r = n;
while(l < n - 1) {
r = n;
int l1 = find(l, r, sum1, x, l);
int l2 = find(l, r, sum2, x, l);
int s1 = -1;
if (l1 != n) {
s1 = sum1[l1];
if (l >= 0) s1 -= sum1[l];
}
int s2 = -1;
if (l2 != n) {
s2 = sum2[l2];
if (l >= 0) s2 -= sum2[l];
}
if (Math.max(s1, s2) < x) return -1;
// System.out.println(l1 + " " + l2);
if (l1 < l2) {
w1++;
last = 1;
}else {
w2++;
last = 0;
}
l = Math.min(l1, l2);
}
if (w1 == w2) return -1;
if (w1 > w2 && last == 0) return -1;
if (w1 < w2 && last == 1) return -1;
return Math.max(w1, w2);
// System.out.println("won=" + won + " lost=" + lost + " last=" + last);
// System.out.println("-----------------------------");
// if (lost >= won || last == 0) return -1;
// return won;
}
private int find(int l, int r, int []sum, int x, int L) {
while(r - l > 1) {
int m = l + (r - l) / 2;
int s = sum[m];
if (L >= 0) s -= sum[L];
if (x <= s) {
r = m;
}else {
l = m;
}
}
return r;
}
class P implements Comparable<P> {
int s, t;
public P(int s, int t) {
this.s = s;
this.t = t;
}
public int compareTo(P other) {
if (this.s < other.s) return -1;
if (this.s > other.s) return 1;
return this.t - other.t;
}
public String toString() {
return this.s + " " + this.t;
}
}
public static void main(String args[]) throws Exception{
new Main().run();
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
81ce4ae0848057c21dbc34ebd0c65a21
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 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.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static class Sort implements Comparable<Sort> {
int s, t;
public int compareTo(Sort arg0) {
if (this.s==arg0.s)
return this.t-arg0.t;
return this.s-arg0.s;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int[]a = new int[n+1];
ArrayList<Integer>ones = new ArrayList<>();
ArrayList<Integer>two = new ArrayList<>();
int[]cnt1 = new int[n+1], cnt2 = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
cnt1[i] = cnt1[i-1];
cnt2[i] = cnt2[i-1];
if (a[i]==1) {
ones.add(i);
cnt1[i]++;
}
else {
two.add(i);
cnt2[i]++;
}
}
int INF = (int) 1e9;
Sort[]ans = new Sort[n+1];
int cnt = 0;
for (int s = 1; s <= n; s++) {
int begin = 1;
int ind1 = 0, ind2 = 0;
int first_point = 0, second_point = 0;
boolean ok = false;
int last = 0;
while (begin <= n) {
int k1 = INF;
int prev = begin;
if (ind1+s <= ones.size()) {
k1 = ones.get(ind1+s-1);
}
int k2 = INF;
int q = 0;
if (ind2+s <= two.size()) {
k2 = two.get(ind2+s-1);
}
if (k1 != INF && k2 != INF) {
if (k1 < k2) {
first_point++;
begin = k1+1;
q = 1;
if (begin==n+1) {
ok = true;
last = 1;
}
}
else {
q = 2;
second_point++;
begin = k2+1;
if (begin==n+1) {
ok = true;
last = 2;
}
}
}
else if (k1 != INF) {
first_point++;
begin = k1+1;
q = 1;
if (begin==n+1) {
ok = true;
last = 1;
}
}
else if (k2 != INF) {
second_point++;
q = 2;
begin = k2+1;
if (begin==n+1) {
ok = true;
last = 2;
}
}
else
break;
if (q==1) {
ind1 += s;
ind2 += cnt2[begin-1]-cnt2[prev-1];
}
else {
ind2 += s;
ind1 += cnt1[begin-1]-cnt1[prev-1];
}
// while (ind1 < ones.size() && ones.get(ind1) < begin)
// ind1++;
// while (ind2 < two.size() && two.get(ind2) < begin)
// ind2++;
}
if (ok) {
if (first_point > second_point && last==1 || second_point > first_point && last==2) {
ans[++cnt] = new Sort();
ans[cnt].t = s;
ans[cnt].s = Math.max(first_point, second_point);
}
}
}
Arrays.sort(ans, 1, cnt+1);
pw.println(cnt);
for (int i = 1; i <= cnt; i++) {
pw.println(ans[i].s+" "+ans[i].t);
}
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
a364fb48e2dc814ad7f9f88f69f89369
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CopyOfB {
void run() {
int n = in.nextInt();
int[] a = new int[n];
int[] c = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() - 1;
if (a[i] < 0 || a[i] > 1) {
throw new RuntimeException();
}
c[i + 1] = c[i] + a[i];
}
List<Pair> ans = new ArrayList<>();
for (int t = n; t >= 1; t--) {
int score0 = 0;
int score1 = 0;
for (int i = 0;;) {
int win1 = c[n] - c[i];
int win0 = n - i - win1;
if (win1 < t && win0 < t) {
break;
}
int low = i;
int high = n;
while (low + 1 < high) {
int mid = (low + high) / 2;
win1 = c[mid] - c[i];
win0 = mid - i - win1;
if (win1 < t && win0 < t) {
low = mid;
} else {
high = mid;
}
}
win1 = c[high] - c[i];
win0 = high - i - win1;
int lastWin;
if (a[high - 1] == 0) {
score0++;
lastWin = 0;
} else {
score1++;
lastWin = 1;
}
i = high;
if (i == n) {
if (lastWin == 0 && score0 > score1) {
ans.add(new Pair(score0, t));
}
if (lastWin == 1 && score0 < score1) {
ans.add(new Pair(score1, t));
}
break;
}
}
}
Collections.sort(ans);
out.println(ans.size());
for (Pair s : ans) {
out.println(s);
}
}
class Pair implements Comparable<Pair> {
int s, t;
public Pair(int s, int t) {
this.s = s;
this.t = t;
}
@Override
public int compareTo(Pair o) {
if (s != o.s) {
return Integer.compare(s, o.s);
}
return Integer.compare(t, o.t);
}
@Override
public String toString() {
return s + " " + t;
}
}
static boolean stdStreams = true;
static String fileName = CopyOfB.class.getSimpleName().replaceFirst("_.*", "").toLowerCase();
static String inputFileName = fileName + ".in";
static String outputFileName = fileName + ".out";
static MyScanner in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
BufferedReader br;
if (stdStreams) {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
br = new BufferedReader(new FileReader(inputFileName));
out = new PrintWriter(outputFileName);
}
in = new MyScanner(br);
int tests = 1;//in.nextInt();
for (int test = 0; test < tests; test++) {
new CopyOfB().run();
}
br.close();
out.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
1b1930f1ba9cb2c77f0396728b33baf7
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class B {
int n;
int[] a;
int[] c;
int playFrom(int i, int t) {
int low = i;
int high = n + 1;
while (low + 1 < high) {
int m = (low + high) / 2;
int win1 = c[m] - c[i];
int win0 = m - i - win1;
if (Math.max(win0, win1) < t) {
low = m;
} else {
high = m;
}
}
return high;
}
void run() {
n = in.nextInt();
a = new int[n];
c = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() - 1;
c[i + 1] = c[i] + a[i];
}
List<Pair> ans = new ArrayList<>();
for (int t = 1; t <= n; t++) {
int[] score = new int[2];
for (int i = 0; i < n;) {
int j = playFrom(i, t);
if (j > n) {
break;
}
int winner = a[j - 1];
score[winner]++;
if (j == n) {
if (score[winner] > score[1 - winner]) {
ans.add(new Pair(score[winner], t));
}
break;
}
i = j;
}
}
Collections.sort(ans);
out.println(ans.size());
for (Pair p : ans) {
out.println(p);
}
}
class Pair implements Comparable<Pair> {
int s, t;
public Pair(int s, int t) {
this.s = s;
this.t = t;
}
@Override
public int compareTo(Pair o) {
if (s != o.s) {
return Integer.compare(s, o.s);
}
return Integer.compare(t, o.t);
}
@Override
public String toString() {
return s + " " + t;
}
}
static boolean stdStreams = true;
static String fileName = B.class.getSimpleName().replaceFirst("_.*", "").toLowerCase();
static String inputFileName = fileName + ".in";
static String outputFileName = fileName + ".out";
static MyScanner in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
BufferedReader br;
if (stdStreams) {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
br = new BufferedReader(new FileReader(inputFileName));
out = new PrintWriter(outputFileName);
}
in = new MyScanner(br);
int tests = 1;//in.nextInt();
for (int test = 0; test < tests; test++) {
new B().run();
}
br.close();
out.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
45dca65de4ebc86cc85622977a36e371
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main implements Runnable {
class Res{
int s, t;
Res(int s, int t){this.s = s; this.t = t;}
}
public void solve() throws IOException {
int N = nextInt();
int[] a = new int[N];
for(int i = 0; i < N; i++) a[i] = nextInt();
int[] first = new int[N+1];
int[] second = new int[N+1];
for(int i = 0;i < N; i++){
if(a[i] == 1) first[i+1] = first[i] + 1;
else first[i+1] = first[i];
if(a[i] == 2) second[i+1] = second[i] + 1;
else second[i+1] = second[i];
}
// debug(first);
// debug(second);
ArrayList<Res> al = new ArrayList<>();
outer: for(int t = 1; t <= N; t++){
int wins0 = 0, wins1 = 0;
int ptr = 0;
int last = -1;
while(ptr < N){
int firstAt = search(first[ptr] + t, first);
int secondAt = search(second[ptr] + t, second);
// System.out.println(" " + t + " " +firstAt + " " + secondAt);
int min = Math.min(firstAt, secondAt);
if(min > N){
continue outer;
}
if(firstAt < secondAt){
wins0++;
ptr = firstAt;
last = 0;
}
else{
wins1++;
ptr = secondAt;
last = 1;
}
}
if(wins0 != wins1){
if(wins0 > wins1 && last == 0) al.add(new Res(wins0, t));
else if(wins1 > wins0 && last == 1) al.add(new Res(wins1, t));
}
}
Collections.sort(al, new Comparator<Res>(){
public int compare(Res a, Res b){
int T = a.s - b.s;
if(T == 0) T = a.t - b.t;
return T;
}
});
out.println(al.size());
for(Res r : al)out.println(r.s + " " + r.t);
}
public int search(int value, int[] a){
int lo = 0, hi = a.length;
while(hi - lo > 1){
int mid = (lo + hi) / 2;
if(a[mid] >= value) hi = mid;
else lo = mid;
}
return hi;
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void debug(Object... arr){
System.out.println(Arrays.deepToString(arr));
}
public void print1Int(int[] a){
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
6c42a9227a528776816db26adb829309
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class E {
FastScanner in;
PrintWriter out;
class Result implements Comparable<Result> {
int inSet, inParty;
public Result(int inSet, int inParty) {
super();
this.inSet = inSet;
this.inParty = inParty;
}
@Override
public int compareTo(Result o) {
if (inSet != o.inSet)
return Integer.compare(inSet, o.inSet);
return Integer.compare(inParty, o.inParty);
}
}
public void solve() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
int[] s = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt() - 1;
s[i] = a[i];
if (i != 0)
s[i] += s[i - 1];
}
TreeSet<Result> results = new TreeSet<>();
for (int inParty = 1; inParty <= n; ++inParty) {
int l = 0;
int inSet = -1;
boolean bad = false;
int cnt1 = 0, cnt0 = 0;
int lastWin = 0;
while (l != n) {
int bef0 = 0, bef1 = 0;
if (l != 0) {
bef0 = (l - s[l - 1]);
bef1 = s[l - 1];
}
// (cl; cr]
int cl = l - 1, cr = n - 1;
while (cr - cl > 1) {
int cm = (cl + cr) / 2;
int now1 = s[cm] - bef1;
int now0 = (cm + 1 - s[cm] - bef0);
if (now1 >= inParty || now0 >= inParty)
cr = cm;
else
cl = cm;
}
int binAns = cr;
int now1 = s[binAns] - bef1;
int now0 = (binAns + 1 - s[binAns] - bef0);
if (now1 >= inParty) {
cnt1++;
l = binAns + 1;
lastWin = 1;
} else if (now0 >= inParty) {
cnt0++;
l = binAns + 1;
lastWin = 0;
} else {
bad = true;
break;
}
}
if (cnt1 > cnt0 && lastWin == 1)
inSet = cnt1;
else if (cnt0 > cnt1 && lastWin == 0)
inSet = cnt0;
if (!bad && inSet != -1)
results.add(new Result(inSet, inParty));
}
out.println(results.size());
for (Result res : results)
out.println(res.inSet + " " + res.inParty);
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] arg) {
new E().run();
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
5b3fd04232fceeff6eb306ca4f08eed4
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.OutputStream;
import java.util.Collections;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Comparator;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - [email protected]
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
IntList firstList = new IntArrayList();
IntList secondList = new IntArrayList();
for (int i = 0; i < count; i++) {
if (in.readInt() == 1)
firstList.add(i);
else
secondList.add(i);
}
int[] first = firstList.toArray();
int[] second = secondList.toArray();
List<Pair<Integer, Integer>> answer = new ArrayList<Pair<Integer, Integer>>();
for (int i = 1; i <= count; i++) {
int at = -1;
int firstSets = 0;
int secondSets = 0;
int lastWon = -1;
boolean isOk = true;
while (at < count - 1) {
int firstPosition = Arrays.binarySearch(first, at);
int secondPosition = Arrays.binarySearch(second, at);
if (firstPosition < 0)
firstPosition = -firstPosition - 2;
if (secondPosition < 0)
secondPosition = -secondPosition - 2;
firstPosition += i;
secondPosition += i;
if (firstPosition < first.length) {
if (secondPosition < second.length) {
if (first[firstPosition] < second[secondPosition]) {
at = first[firstPosition];
firstSets++;
lastWon = 0;
}
else {
at = second[secondPosition];
secondSets++;
lastWon = 1;
}
}
else {
at = first[firstPosition];
firstSets++;
lastWon = 0;
}
}
else {
if (secondPosition < second.length) {
at = second[secondPosition];
secondSets++;
lastWon = 1;
}
else {
isOk = false;
break;
}
}
}
if (isOk) {
if (firstSets > secondSets && lastWon == 0)
answer.add(Pair.makePair(firstSets, i));
else if (secondSets > firstSets && lastWon == 1)
answer.add(Pair.makePair(secondSets, i));
}
}
Collections.sort(answer);
out.printLine(answer.size());
for (Pair x : answer)
out.printLine(x.first, x.second);
}
}
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
abstract class IntList extends IntCollection implements Comparable<IntList> {
private static final int INSERTION_THRESHOLD = 8;
public abstract int get(int index);
public abstract void set(int index, int value);
public IntIterator iterator() {
return new IntIterator() {
private int size = size();
private int index = 0;
public int value() throws NoSuchElementException {
if (!isValid())
throw new NoSuchElementException();
return get(index);
}
public void advance() throws NoSuchElementException {
if (!isValid())
throw new NoSuchElementException();
index++;
}
public boolean isValid() {
return index < size;
}
};
}
private void swap(int first, int second) {
if (first == second)
return;
int temp = get(first);
set(first, get(second));
set(second, temp);
}
public IntSortedList inPlaceSort(IntComparator comparator) {
quickSort(0, size() - 1, size(), comparator);
return new IntSortedArray(this, comparator);
}
private void quickSort(int from, int to, int remaining, IntComparator comparator) {
if (to - from < INSERTION_THRESHOLD) {
insertionSort(from, to, comparator);
return;
}
if (remaining == 0) {
heapSort(from, to, comparator);
return;
}
remaining >>= 1;
int pivotIndex = (from + to) >> 1;
int pivot = get(pivotIndex);
swap(pivotIndex, to);
int storeIndex = from;
int equalIndex = to;
for (int i = from; i < equalIndex; i++) {
int value = comparator.compare(get(i), pivot);
if (value < 0)
swap(storeIndex++, i);
else if (value == 0)
swap(--equalIndex, i--);
}
quickSort(from, storeIndex - 1, remaining, comparator);
for (int i = equalIndex; i <= to; i++)
swap(storeIndex++, i);
quickSort(storeIndex, to, remaining, comparator);
}
private void heapSort(int from, int to, IntComparator comparator) {
for (int i = (to + from - 1) >> 1; i >= from; i--)
siftDown(i, to, comparator, from);
for (int i = to; i > from; i--) {
swap(from, i);
siftDown(from, i - 1, comparator, from);
}
}
private void siftDown(int start, int end, IntComparator comparator, int delta) {
int value = get(start);
while (true) {
int child = ((start - delta) << 1) + 1 + delta;
if (child > end)
return;
int childValue = get(child);
if (child + 1 <= end) {
int otherValue = get(child + 1);
if (comparator.compare(otherValue, childValue) > 0) {
child++;
childValue = otherValue;
}
}
if (comparator.compare(value, childValue) >= 0)
return;
swap(start, child);
start = child;
}
}
private void insertionSort(int from, int to, IntComparator comparator) {
for (int i = from + 1; i <= to; i++) {
int value = get(i);
for (int j = i - 1; j >= from; j--) {
if (comparator.compare(get(j), value) <= 0)
break;
swap(j, j + 1);
}
}
}
public int hashCode() {
int hashCode = 1;
for (IntIterator i = iterator(); i.isValid(); i.advance())
hashCode = 31 * hashCode + i.value();
return hashCode;
}
public boolean equals(Object obj) {
if (!(obj instanceof IntList))
return false;
IntList list = (IntList)obj;
if (list.size() != size())
return false;
IntIterator i = iterator();
IntIterator j = list.iterator();
while (i.isValid()) {
if (i.value() != j.value())
return false;
i.advance();
j.advance();
}
return true;
}
public int compareTo(IntList o) {
IntIterator i = iterator();
IntIterator j = o.iterator();
while (true) {
if (i.isValid()) {
if (j.isValid()) {
if (i.value() != j.value()) {
if (i.value() < j.value())
return -1;
else
return 1;
}
} else
return 1;
} else {
if (j.isValid())
return -1;
else
return 0;
}
i.advance();
j.advance();
}
}
public IntSortedList sort(IntComparator comparator) {
return new IntArray(this).inPlaceSort(comparator);
}
}
class IntArrayList extends IntList {
private int[] array;
private int size;
public IntArrayList() {
this(10);
}
public IntArrayList(int capacity) {
array = new int[capacity];
}
public int get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException();
return array[index];
}
public void set(int index, int value) {
if (index >= size)
throw new IndexOutOfBoundsException();
array[index] = value;
}
public int size() {
return size;
}
public void add(int value) {
ensureCapacity(size + 1);
array[size++] = value;
}
public void ensureCapacity(int newCapacity) {
if (newCapacity > array.length) {
int[] newArray = new int[Math.max(newCapacity, array.length << 1)];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
}
public int[] toArray() {
int[] array = new int[size];
System.arraycopy(this.array, 0, array, 0, size);
return array;
}
}
abstract class IntCollection {
public abstract IntIterator iterator();
public abstract int size();
public abstract void add(int value);
public int[] toArray() {
int size = size();
int[] array = new int[size];
int i = 0;
for (IntIterator iterator = iterator(); iterator.isValid(); iterator.advance())
array[i++] = iterator.value();
return array;
}
}
class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static<U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>)first).compareTo(o.first);
if (value != 0)
return value;
return ((Comparable<V>)second).compareTo(o.second);
}
}
interface IntIterator {
public int value() throws NoSuchElementException;
/*
* @throws NoSuchElementException only if iterator already invalid
*/
public void advance() throws NoSuchElementException;
public boolean isValid();
}
abstract class IntSortedList extends IntList {
protected final IntComparator comparator;
protected IntSortedList(IntComparator comparator) {
this.comparator = comparator;
}
public void set(int index, int value) {
throw new UnsupportedOperationException();
}
public void add(int value) {
throw new UnsupportedOperationException();
}
public IntSortedList inPlaceSort(IntComparator comparator) {
if (comparator == this.comparator)
return this;
throw new UnsupportedOperationException();
}
public IntSortedList sort(IntComparator comparator) {
if (comparator == this.comparator)
return this;
return super.sort(comparator);
}
protected void ensureSorted() {
int size = size();
if (size == 0)
return;
int last = get(0);
for (int i = 1; i < size; i++) {
int current = get(i);
if (comparator.compare(last, current) > 0)
throw new IllegalArgumentException();
last = current;
}
}
}
interface IntComparator {
public int compare(int first, int second);
}
class IntSortedArray extends IntSortedList {
private final int[] array;
public IntSortedArray(IntCollection collection, IntComparator comparator) {
super(comparator);
array = new int[collection.size()];
int i = 0;
for (IntIterator iterator = collection.iterator(); iterator.isValid(); iterator.advance())
array[i++] = iterator.value();
ensureSorted();
}
public int get(int index) {
return array[index];
}
public int size() {
return array.length;
}
}
class IntArray extends IntList {
private final int[] array;
public IntArray(IntCollection collection) {
array = new int[collection.size()];
int i = 0;
for (IntIterator iterator = collection.iterator(); iterator.isValid(); iterator.advance())
array[i++] = iterator.value();
}
public int get(int index) {
return array[index];
}
public void set(int index, int value) {
array[index] = value;
}
public int size() {
return array.length;
}
public void add(int value) {
throw new UnsupportedOperationException();
}
public int[] toArray() {
return array;
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
77a1d1ae86395423f434294b9fdfa43b
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.*;
public class b {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
n = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++) data[i] = input.nextInt();
TreeSet<Pair> res = new TreeSet<Pair>();
precomp(data);
for(int i = 1; i<=n; i++)
{
int s = getS(i, data);
if(s == -1) continue;
res.add(new Pair(s, i));
}
System.out.println(res.size());
for(Pair p: res) System.out.println(p.s+" "+p.t);
}
static class Pair implements Comparable<Pair>
{
int s, t;
public Pair(int ss, int tt)
{
s = ss; t = tt;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(s != o.s) return s - o.s;
return t - o.t;
}
}
static int n;
static int[] getA, getB, scoreA, scoreB;
static void precomp(int[] data)
{
scoreA = new int[n];
scoreB = new int[n];
for(int i = 0; i<n; i++)
{
int lastA = (i == 0 ? 0 : scoreA[i-1]);
int lastB = (i == 0 ? 0 : scoreB[i-1]);
scoreA[i] = data[i] == 1 ? lastA + 1 : lastA;
scoreB[i] = data[i] == 2 ? lastB + 1 : lastB;
}
getA = new int[n];
getB = new int[n];
int atA = 0, atB = 0;
Arrays.fill(getA, n);
Arrays.fill(getB, n);
for(int i = 0; i<n; i++)
{
if(data[i] == 1) getA[atA++] = i;
else getB[atB++] = i;
}
}
static int getS(int t, int[] data)
{
int sa = 0, sb = 0;
boolean end = false;
int usedA = -1, usedB = -1;
//int at = 0;
while(true)
{
int nextA = usedA + t >= n ? n : getA[usedA + t];
int nextB = usedB + t >= n ? n : getB[usedB + t];
int nextPos = Math.min(nextA, nextB);
if(nextPos >= n) break;
if(data[nextPos] == 1)
{
sa++;
}
else sb++;
usedA = scoreA[nextPos]-1;
usedB = scoreB[nextPos]-1;
if(nextPos == n-1) end = true;
//System.out.println(nextPos);
//at = nextPos;
}
//System.out.println(t+" "+sa+" "+sb+" "+end);
if(!end) return -1;
if(data[n-1] == 1 && sa > sb) return sa;
if(data[n-1] == 2 && sb> sa) return sb;
return -1;
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
faa7a615d386d8fc457ea4bff24475c3
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.io.BufferedReader;
import java.util.Map;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class Element implements Comparable<Element>{
public int s,t;
public Element(int s, int t){
this.s = s;
this.t = t;
}
public int compareTo(Element o) {
if (s < o.s){
return -1;
} else if (s > o.s){
return 1;
} else {
return ((Integer)t).compareTo(o.t);
}
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i=0; i<n; i++){
a[i] = in.nextInt();
}
calc(n, a, out);
}
private void calc(int n, int[] a, PrintWriter out) {
Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
int[] values1 = new int[a.length];
int[] values2 = new int[a.length];
preCalc(a, map1, map2, values1, values2);
List<Element> sol = new ArrayList<Element>();
for (int t=1; t<=n; t++){
int s = check(a, t , map1, map2, values1, values2);
if (s != -1){
sol.add(new Element(s, t));
}
}
Collections.sort(sol);
printSol(sol, out);
}
private void preCalc(int[] a, Map<Integer, Integer> map1, Map<Integer, Integer> map2, int[] values1, int[] values2) {
int curr1 = 0;
int curr2 = 0;
for (int i=0; i<a.length; i++){
if (a[i] == 1){
curr1++;
map1.put(curr1, i);
} else {
curr2++;
map2.put(curr2, i);
}
values1[i] = curr1;
values2[i] = curr2;
}
}
private int check(int[] a, int t, Map<Integer, Integer> map1, Map<Integer, Integer> map2, int[] values1, int[] values2) {
int curr1 = 0;
int curr2 = 0;
int sets1 = 0;
int sets2 = 0;
int prevSets1 = 0;
int prevSets2 = 0;
int index = -1;
while (map1.containsKey(curr1+t) || map2.containsKey(curr2+t)){
int index1 = (map1.containsKey(curr1+t)) ? map1.get(curr1+t) : Integer.MAX_VALUE;
int index2 = (map2.containsKey(curr2+t)) ? map2.get(curr2+t) : Integer.MAX_VALUE;
prevSets1 = sets1;
prevSets2 = sets2;
if (index1 < index2){
index = index1;
curr1 += t;
sets1++;
curr2 = values2[index1];
} else {
index = index2;
curr2 += t;
sets2++;
curr1 = values1[index2];
}
}
if (index == a.length-1 && Math.max(prevSets1, prevSets2) != Math.max(sets1, sets2)){
return Math.max(sets1, sets2);
}
return -1;
}
private void printSol(List<Element> sol, PrintWriter out) {
out.println(sol.size());
for (int i=0; i<sol.size(); i++){
out.println(sol.get(i).s + " " + sol.get(i).t);
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
}
public String next(){
while (tokenizer == null || !tokenizer.hasMoreTokens()){
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException("FATAL ERROR", e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.valueOf(next());
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
0d1333a05fbea02fe39162334bc8c2d0
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.awt.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class solver implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
String delim = " ";
String readString() throws IOException {
try {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken(delim);
} catch (Exception e) {
return null;
}
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
Point readPoint() throws IOException {
return new Point(readInt(), readInt());
}
// ----------------------------------
class Answer implements Comparable<Answer>{
int s;
int t;
Answer(int s, int t){
this.s = s;
this.t = t;
}
@Override
public int compareTo(Answer o) {
if (s != o.s) return s - o.s;
return t - o.t;
}
@Override
public String toString() {
return s+" "+t;
}
}
int[] first;
int[] second;
int[] a;
int n;
int bs(int[] rasp, int start, int last, int cnt) {
int l = Math.max(cnt - 1, 1);
int r = 3 * cnt;
int ans = -1;
while (l <= r) {
int mid = (l + r) / 2;
int index = start + mid - 1;
if (index >= n) {
r = mid - 1;
continue;
}
int cur = rasp[index] - last;
if (cur == cnt) {
ans = index;
r = mid - 1;
}
if (cur < cnt) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
int check(int cnt){
int win1 = 0;
int win2 = 0;
int last1 = 0;
int last2 = 0;
int lastwinner = -1;
for (int j = 0; j < n;){
int index1 = bs(first,j,last1,cnt);
int index2 = bs(second,j,last2,cnt);
if (index1 == -1 && index2 == -1) return -1;
int wi = 0;
if (index2 == -1){
wi = index1;
lastwinner = 1;
win1++;
} else{
if (index1 == -1){
wi = index2;
lastwinner = 2;
win2++;
} else{
if (index1 < index2){
wi = index1;
lastwinner = 1;
win1++;
}else{
wi = index2;
lastwinner = 2;
win2++;
}
}
}
j = wi + 1;
last1 = first[wi];
last2 = second[wi];
}
if (win1 == win2) return -1;
if (lastwinner == 1 && win2 > win1) return -1;
if (lastwinner == 2 && win2 < win1) return -1;
return Math.max(win1, win2);
}
// ----------------------------------------
void solve() throws NumberFormatException, IOException {
n = readInt();
a = new int[n];
first = new int[n];
second = new int[n];
for (int i=0;i<n;i++){
int x = readInt();
a[i] = x;
if (x == 1){
first[i] = 1;
} else{
second[i] = 1;
}
if (i > 0){
first[i] += first[i-1];
second[i] += second[i-1];
}
}
ArrayList<Answer> list = new ArrayList<>();
for (int i=1;i<=2*n;i++){
int x = check(i);
if (x > 0){
list.add(new Answer(x, i));
}
}
Collections.sort(list);
out.println(list.size());
for (Answer ans : list){
out.println(ans);
}
}
// ----------------------------------------
public static void main(String[] args) {
new Thread(null, new solver(), "", 256 * (1L << 20)).start();
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
try {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
// in = new BufferedReader(new FileReader("caravan.in"));
// out = new PrintWriter("caravan.out");
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
} catch (Throwable e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
solve();
out.close();
timeEnd = System.currentTimeMillis();
if (!ONLINE_JUDGE) System.err.println("Time = " + (timeEnd - timeBegin));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
long timeBegin, timeEnd;
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
f4576065d023dc7f273fc63b8ca4f87b
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class BMain {
String noResultMessage = "NoResult";
Parser in = new Parser();
PrintWriter out;
int n = in.nextInteger();
int[][] first = new int[17][140000];
int[][] second = new int[17][140000];
static class Answer {
final int t;
final int s;
Answer(int t, int s) {
this.t = t;
this.s = s;
}
}
int nextRound(int start, int t){
int cnt1 = 0;
int cnt2 = 0;
int i;
for(i = 0; i < 17; ++i){
if((start & (1<<i)) == 0)continue;
int d1 = first[i][start>>i];
int d2 = second[i][start>>i];
if(d1+cnt1 >= t)break;
if(d2+cnt2 >= t)break;
cnt1 += d1;
cnt2 += d2;
start += 1<<i;
if(start >= n)return -1;
}
for(--i; i >= 0; --i){
int d1 = first[i][start>>i];
int d2 = second[i][start>>i];
if(d1+cnt1 >= t)continue;
if(d2+cnt2 >= t)continue;
cnt1 += d1;
cnt2 += d2;
start += 1<<i;
if(start >= n)return -1;
}
int d1 = first[0][start];
int d2 = second[0][start++];
if(d1+cnt1 == t)return start<<1;
if(d2+cnt2 == t)return (start<<1)+1;
return -1;
}
public void solve() {
for(int i = 0; i < n; ++i){
int[][] curr = in.nextInteger() == 1 ? first : second;
int t = i;
for(int j = 0; j < 17; ++j){
++curr[j][t];
t >>= 1;
}
}
ArrayList<Answer> answers = new ArrayList<Answer>();
for(int t = n; t > 0 ; --t){
int cnt1 = 0;
int cnt2 = 0;
int start = 0;
while((start = nextRound(start, t)) > 0){
boolean isFirst = (start&1) == 0;
if(isFirst)cnt1++; else cnt2++;
start >>= 1;
if(start == n){
if(cnt1 != cnt2 && Math.max(cnt1, cnt2) == (isFirst ? cnt1 : cnt2)){
answers.add(new Answer(t, Math.max(cnt1, cnt2)));
}
break;
}
}
}
out.println(answers.size());
Collections.sort(answers, new Comparator<Answer>() {
@Override
public int compare(Answer o1, Answer o2) {
return o1.s == o2.s ? Integer.compare(o1.t, o2.t) : Integer.compare(o1.s, o2.s);
}
});
for(Answer ans : answers){
out.println("" + ans.s + " " + ans.t);
}
}
static public class Parser{
Scanner scanner;
public Parser() {
scanner = new Scanner(System.in).useLocale(Locale.ENGLISH);
}
public Parser(String str) {
scanner = new Scanner(str).useLocale(Locale.ENGLISH);
}
long nextLong(){
return scanner.nextLong();
}
int nextInteger(){
return scanner.nextInt();
}
double nextDouble(){
return scanner.nextDouble();
}
String nextLine(){
return scanner.nextLine();
}
String next(){
return scanner.next();
}
int[] nextIntegers(int count){
int[] result = new int[count];
for(int i = 0; i < count; ++i){
result[i] = nextInteger();
}
return result;
}
long[] nextLongs(int count){
long[] result = new long[count];
for(int i = 0; i < count; ++i){
result[i] = nextLong();
}
return result;
}
int[][] nextIntegers(int fields, int count){
int[][] result = new int[fields][count];
for(int c = 0; c < count; ++c){
for(int i = 0; i < fields; ++i){
result[i][c] = nextInteger();
}
}
return result;
}
}
void noResult(){
throw new NoResultException();
}
void noResult(String str){
throw new NoResultException(str);
}
void run(){
try{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
out = new PrintWriter(outStream);
solve();
out.close();
System.out.print(outStream.toString());
} catch (NoResultException exc){
System.out.print(null == exc.response ? noResultMessage : exc.response);
}
}
public static void main(String[] args) {
new BMain().run();
}
public static class NoResultException extends RuntimeException{
private String response;
public NoResultException(String response) {
this.response = response;
}
public NoResultException() {
}
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
4f52fa3e1ace91857687053079cf4748
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class D {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
class State implements Comparable<State> {
int s, t;
State(int s, int t) {
this.s = s;
this.t = t;
}
public int compareTo(State x) {
return s - x.s;
}
}
public void run() {
int n = in.nextInt();
int[] a = new int[n+1];
for (int i = 0; i < n; i++) {
a[i + 1] = a[i] + in.nextInt() - 1;
}
List<State> res = new ArrayList<State>();
for (int t = 1; t <= n; t++) {
int k = 0, w0 = 0, w1 = 0;
while (k < n) {
int l = k, r = n;
while (r > l + 1) {
int m = (l + r) / 2;
int c = a[m] - a[k];
c = Math.max(c, m - k - c);
if (c >= t) r = m;
else l = m;
}
int c1 = a[r] - a[k];
int c0 = r - k - c1;
if (c1 == t) w1++;
else if (c0 == t) w0++;
else break;
if (r == n) {
if (w1 > w0 && c1 == t) {
res.add(new State(w1, t));
} else if (w0 > w1 && c0 == t) {
res.add(new State(w0, t));
}
}
k = r;
}
}
Collections.sort(res);
out.println(res.size());
for (State s : res) out.println(s.s + " " + s.t);
out.close();
}
public static void main(String[] args) {
new D().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
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;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
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();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
afd1f71499b1a316f8574b37c1f3f3ef
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
new Main().solve();
}
private void solve() {
QuickScanner in = new QuickScanner();
int n = in.nextInt();
int[] seq = new int[n];
int[] sum1 = new int[n];
int[] sum2 = new int[n];
int[] firstOccurence1 = new int[n + 1];
int[] firstOccurence2 = new int[n + 1];
Arrays.fill(firstOccurence1, Integer.MAX_VALUE);
Arrays.fill(firstOccurence2, Integer.MAX_VALUE);
for (int i = 0; i < n; i++) {
seq[i] = in.nextInt();
if (seq[i] == 1) {
sum1[i] = 1;
} else {
sum2[i] = 1;
}
if (i > 0) {
sum1[i] += sum1[i - 1];
sum2[i] += sum2[i - 1];
}
if (firstOccurence1[sum1[i]] == Integer.MAX_VALUE) {
firstOccurence1[sum1[i]] = i;
}
if (firstOccurence2[sum2[i]] == Integer.MAX_VALUE) {
firstOccurence2[sum2[i]] = i;
}
}
TreeMap<Integer, TreeSet<Integer>> ans = new TreeMap<Integer, TreeSet<Integer>>();
for (int t = 1; t <= n; t++) {
int i = 0;
int totalWin1 = 0;
int totalWin2 = 0;
int s1 = 0;
int s2 = 0;
int lastWin = -1;
while (i < n) {
int next1 = totalWin1 + t <= n ? firstOccurence1[totalWin1 + t] : Integer.MAX_VALUE;
int next2 = totalWin2 + t <= n ? firstOccurence2[totalWin2 + t] : Integer.MAX_VALUE;
if (next1 == Integer.MAX_VALUE && next2 == Integer.MAX_VALUE) {
break;
}
if (next1 < next2) {
totalWin1 = sum1[next1];
totalWin2 = sum2[next1];
i = next1 + 1;
s1++;
lastWin = 1;
} else {
totalWin1 = sum1[next2];
totalWin2 = sum2[next2];
i = next2 + 1;
s2++;
lastWin = 2;
}
}
if (i == n) {
int s = -1;
if (s1 > s2 && lastWin == 1) {
s = s1;
}
if (s1 < s2 && lastWin == 2) {
s = s2;
}
if (s != -1) {
TreeSet<Integer> helper = ans.get(s);
if (helper == null) {
helper = new TreeSet<Integer>();
ans.put(s, helper);
}
ans.get(s).add(t);
}
}
}
PrintWriter pw = new PrintWriter(System.out);
int tot = 0;
for (Entry<Integer, TreeSet<Integer>> pair : ans.entrySet()) {
tot += pair.getValue().size();
}
pw.println(tot);
for (Entry<Integer, TreeSet<Integer>> pair : ans.entrySet()) {
int s = pair.getKey();
for (int t : pair.getValue()) {
pw.printf("%d %d\n", s, t);
}
}
pw.flush();
}
/*
* A fast Scanner class.
*/
private class QuickScanner {
private BufferedReader bufferedReader = null;
private StringTokenizer stringTokenizer = null;
private String nextHolder = null;
QuickScanner() {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
if (nextHolder != null) {
String next = nextHolder;
nextHolder = null;
return next;
}
try {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
String newLine = bufferedReader.readLine();
if (newLine != null) {
stringTokenizer = new StringTokenizer(newLine);
} else {
return null;
}
}
return stringTokenizer.nextToken();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
6d3c3200a0c6f74a94b8d52a9df3a238
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.List;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
int count1[];
int count2[];
int getCount1(int l, int r) {
return count1[r] - ((l>0)?count1[l-1]:0);
}
int getCount2(int l, int r) {
return count2[r] - ((l>0)?count2[l-1]:0);
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
count1 = new int[n];
count2 = new int[n];
for(int i=0;i<n;i++) {
int t = in.nextInt();
if(t==1)
count1[i]++;
else
count2[i]++;
if(i!=0) {
count1[i] += count1[i - 1];
count2[i] += count2[i-1];
}
}
ArrayList<Pair<Integer,Integer>> ans = new ArrayList<Pair<Integer, Integer>>();
int last = -1;
for(int t = 1 ;t<=n;t++) {
int curS = 0;
boolean failed = false;
int rounds1 = 0;
int rounds2 = 0;
while(curS<n) {
// search for last index
int L = curS;
int R = n-1;
while(L<R-1) {
int C = (L+R)/2;
if(getCount1(curS,C) >=t || getCount2(curS,C)>=t) {
R = C;
} else
L = C;
}
// R is supposed to store the answer
if(getCount1(curS,L) >=t || getCount2(curS,L)>=t)
R = L;
if(getCount1(curS,R) >=t || getCount2(curS,R)>=t) {
if(getCount1(curS,R) >=t ) {
++rounds1;
last = 1;
}
else {
++rounds2;
last = 2;
}
curS = R+1;
} else {
// we failed, there is no assignment
failed = true;
break;
}
}
if(rounds1 == rounds2)
failed = true;
if(last == 1 && rounds2>rounds1)
failed = true;
if(last == 2 && rounds1 > rounds2)
failed = true;
if(!failed) {
ans.add(new Pair<Integer, Integer>(Math.max(rounds1,rounds2), t));
}
}
Collections.sort(ans);
out.println(ans.size());
for(Pair<Integer,Integer> a:ans) {
out.println(a.first+" "+a.second);
}
}
}
class InputReader {
private InputStream stream;
int curCharIndex = 0;
int charsInBuf = 0;
byte buf[] = new byte[16*1024];
public InputReader(InputStream stream) {
this.stream = stream;
}
public int readChar() {
if (curCharIndex >= charsInBuf) {
curCharIndex = 0;
try {
charsInBuf = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (charsInBuf <= 0)
return -1;
}
return buf[curCharIndex++];
}
public int nextInt() {
int c;
do {
c = readChar();
}while(isWhitespace(c));
int sign = 1;
if (c == '-') {
c = readChar();
sign = -1;
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = readChar();
} while (!isWhitespace(c) && c!=-1);
return sign * res;
}
/*
* For the purpose of compatibilty with Chelper Chrome extension
*/
private boolean isWhitespace(int c) {
return c==' ' || c=='\n'|| c=='\r' || c=='\t';
}
}
class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> {
public final FIRST first;
public final SECOND second;
public Pair(FIRST first, SECOND second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair<FIRST, SECOND> o) {
int cmp = compare(first, o.first);
return cmp == 0 ? compare(second, o.second) : cmp;
}
private static int compare(Object o1, Object o2) {
return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1
: ((Comparable) o1).compareTo(o2);
}
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair) obj).first)
&& equal(second, ((Pair) obj).second);
}
private boolean equal(Object o1, Object o2) {
return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2));
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
adfbbda811f430c0b09b70aa386b49c0
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.List;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
class Pair implements Comparable<Pair> {
int s;
int t;
public Pair(int s, int t) {
this.s = s;
this.t = t;
}
public int compareTo(Pair pair) {
int c = Integer.valueOf(this.s).compareTo(pair.s);
return (c == 0 ? Integer.valueOf(this.t).compareTo(pair.t) : c);
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.readInt() - 1;
}
int winner = a[n];
int[][] sum = new int[2][n + 1];
int[][] idx = new int[2][2 * n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 2; j++) {
sum[j][i] = sum[j][i - 1] + (a[i] == j ? 1 : 0);
if (idx[j][sum[j][i]] == 0) {
idx[j][sum[j][i]] = i;
}
}
}
ArrayList<Pair> res = new ArrayList<Pair>();
for (int t = 1; t <= Math.max(sum[0][n], sum[1][n]); t++) {
int ptr = 0;
int[] cnt = new int[2];
while (ptr < n) {
int i = idx[0][sum[0][ptr] + t];
int j = idx[1][sum[1][ptr] + t];
if ((i > ptr && j <= ptr) || i > 0 && (i < j)) {
ptr = i;
cnt[0]++;
}
else if ((j > ptr && i <= ptr) || j > 0 && (j < i)) {
ptr = j;
cnt[1]++;
}
else {
break;
}
}
if (ptr == n) {
if (cnt[winner] > cnt[winner ^ 1]) {
res.add(new Pair(cnt[winner], t));
}
}
}
Collections.sort(res);
out.printLine(res.size());
for (Pair p : res) {
out.printLine(p.s + " " + p.t);
}
}
}
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
ce6507c29fdb4073ef861742949d7da6
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
//package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
public class B {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
StringTokenizer stringTokenizer;
B() throws IOException {
// reader = new BufferedReader(new FileReader("cycle2.in"));
// writer = new PrintWriter(new FileWriter("cycle2.out"));
}
String next() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
int[][] mul(int[][] a, int[][] b) {
int[][] result = new int[2][2];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
result[i][j] = sum(result[i][j], product(a[i][k], b[k][j]));
}
}
}
return result;
}
int[][] pow(int[][] a, int k) {
int[][] result = {{1, 0}, {0, 1}};
while(k > 0) {
if(k % 2 == 1) {
result = mul(result, a);
}
a = mul(a, a);
k /= 2;
}
return result;
}
final int MOD = 1000 * 1000 * 1000 + 7;
int sum(int a, int b) {
a += b;
return a >= MOD ? a - MOD : a;
}
int product(int a, int b) {
return (int)(1l * a * b % MOD);
}
@SuppressWarnings("unchecked")
void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = nextInt();
}
int[][] p = new int[2][n + 1];
for(int i = 1; i <= n; i++) {
for(int j = 0; j < 2; j++) {
p[j][i] = p[j][i - 1] + (a[i - 1] == j + 1 ? 1 : 0);
}
}
int[][] f = new int[2][];
for(int i = 0; i < 2; i++) {
f[i] = new int[2 * n];
Arrays.fill(f[i], Integer.MAX_VALUE);
int index = 0;
for(int j = 0; j < n; j++) {
if(a[j] == i + 1) {
f[i][index++] = j;
}
}
}
class Pair {
int s, t;
Pair(int s, int t) {
this.s = s;
this.t = t;
}
}
List<Pair> answer = new ArrayList<>();
for(int t = 1; t <= n; t++) {
int[] ix = new int[2];
int[] lw = new int[2];
int[] s = new int[2];
int last = -1;
boolean good = true;
while(true) {
boolean finish = true;
for(int i = 0; i < 2; i++) {
if(f[i][ix[i]] != Integer.MAX_VALUE) {
finish = false;
}
lw[i] = ix[i] + t - 1;
}
if(finish) {
break;
}
boolean bad = true;
for(int i = 0; i < 2; i++) {
if(f[i][lw[i]] != Integer.MAX_VALUE) {
bad = false;
}
}
if(bad) {
good = false;
break;
}
for(int i = 0; i < 2; i++) {
if(f[i][lw[i]] < f[i + 1 & 1][lw[i + 1 & 1]]) {
s[i]++;
ix[i] = lw[i] + 1;
ix[i + 1 & 1] = p[i + 1 & 1][f[i][lw[i]]];
last = i;
break;
}
}
}
if(s[0] == s[1]) {
good = false;
}
if(good && s[last] < s[last + 1 & 1]) {
good = false;
}
if(good) {
answer.add(new Pair(Math.max(s[0], s[1]), t));
}
}
Collections.sort(answer, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.s == o2.s) {
return o1.t - o2.t;
}
return o1.s - o2.s;
}
});
writer.println(answer.size());
for (Pair pair : answer) {
writer.println(pair.s + " " + pair.t);
}
writer.close();
}
public static void main(String[] args) throws IOException {
new B().solve();
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
2dca850cd8ce21708d4ddd408791123a
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class Main{
final boolean isFileIO = false;
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
String delim = " ";
public static void main(String[] args) throws IOException {
Main m = new Main();
m.initIO();
m.solve();
m.in.close();
m.out.close();
}
public void initIO() throws IOException {
if(!isFileIO) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("strings.in"));
out = new PrintWriter("strings.out");
}
}
String nextToken() throws IOException {
if(!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken(delim);
}
String readLine() throws IOException {
return in.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
class Pair implements Comparable<Pair>{
int s, t;
public Pair(int s, int t) {
this.s = s;
this.t = t;
}
public int compareTo(Pair a) {
if(this.s < a.s) {
return -1;
}
if(this.s > a.s) {
return 1;
}
if(this.t < a.t) {
return -1;
}
if(this.t > a.t) {
return 1;
}
return 0;
}
}
public void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = nextInt();
}
int[] cnta = new int[n + 1];
int[] cntb = new int[n + 1];
for(int i = 1; i <= n; i++) {
cnta[i] = cnta[i - 1];
cntb[i] = cntb[i - 1];
if(a[i - 1] == 1) {
cnta[i]++;
} else {
cntb[i]++;
}
}
int[] stepa = new int[2 * (n + 1)];
int[] stepb = new int[2 * (n + 1)];
Arrays.fill(stepa, Integer.MAX_VALUE);
Arrays.fill(stepb, Integer.MAX_VALUE);
for(int i = 1, j = 1; i <= n; i++) {
if(a[i - 1] == 1) {
stepa[j++] = i;
}
}
for(int i = 1, j = 1; i <= n; i++) {
if(a[i - 1] == 2) {
stepb[j++] = i;
}
}
ArrayList<Pair> list = new ArrayList<Pair>();
for(int t = 1; t <= n; t++) {
int cura = 0;
int curb = 0;
boolean isOkay = true;
int sa = 0;
int sb = 0;
int last = -1;
while(true) {
int min = Math.min(stepa[cura + t], stepb[curb + t]);
if(min == Integer.MAX_VALUE) {
isOkay = false;
break;
}
if(min == stepa[cura + t]) {
sa++;
cura += t;
curb = cntb[min];
last = 1;
} else {
sb++;
curb += t;
cura = cnta[min];
last = 2;
}
if(min == n) {
break;
}
}
if(isOkay) {
if(last == 1 && sa > sb) {
list.add(new Pair(sa, t));
}
if(last == 2 && sb > sa) {
list.add(new Pair(sb, t));
}
}
}
Collections.sort(list);
out.println(list.size());
for(int i = 0; i < list.size(); i++) {
out.println(list.get(i).s + " " + list.get(i).t);
}
}
}
class Utils {
public static long binpow(long a, long exp, long mod) {
if(exp == 0) {
return 1;
}
if(exp % 2 == 0) {
long temp = binpow(a, exp / 2, mod);
return (temp * temp) % mod;
} else {
return (binpow(a, exp - 1, mod) * a) % mod;
}
}
public static long inv(long a, long mod) {
return binpow(a, mod - 2, mod);
}
public static long addmod(long a, long b, long mod) {
return ((a + b) % mod + mod) % mod;
}
public static long gcd(long a, long b) {
if(b == 0)
return a;
return gcd(b, a % b);
}
//mul must be < 10^18
public static long mulmod(long a, long b, long mod) {
return (a * b + (((a * b) / mod) + 1) * mod) % mod;
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
06c7845f05cad90bc4133c1586ff1f37
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.List;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
static class Pair {
int first;
int second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int[] win = new int[n];
int[][] sum = new int[2][n + 1];
List<Pair> res = new ArrayList<Pair>();
for (int i = 0; i < n; i++) {
win[i] = in.readInt() - 1;
}
++sum[win[0]][1];
for (int i = 1; i < n; i++) {
++sum[win[i]][i + 1];
sum[0][i + 1] += sum[0][i];
sum[1][i + 1] += sum[1][i];
}
for (int t = 1; t <= n; t++) {
int pos = 1;
int[] count = new int[2];
boolean possible = true;
while (pos <= n) {
if (sum[0][n] - sum[0][pos - 1] < t && sum[1][n] - sum[1][pos - 1] < t) {
possible = false;
break;
}
int low = pos;
int high = n;
while (low <= high) {
int mid = (low + high) / 2;
if (Math.max(sum[0][mid] - sum[0][pos - 1], sum[1][mid] - sum[1][pos - 1]) >= t) {
high = mid - 1;
} else {
low = mid + 1;
}
}
++high;
if (sum[0][high] - sum[0][pos - 1] == t) {
++count[0];
} else if (sum[1][high] - sum[1][pos - 1] == t) {
++count[1];
} else {
throw new RuntimeException();
}
pos = high + 1;
}
if (possible && count[0] != count[1]) {
if (count[0] > count[1] && win[n - 1] == 0) {
res.add(new Pair(count[0], t));
} else if (count[1] > count[0] && win[n - 1] == 1) {
res.add(new Pair(count[1], t));
}
}
}
Collections.sort(res, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if (o1.first == o2.first)
return o1.second - o2.second;
else
return o1.first - o2.first;
}
});
out.printLine(res.size());
for (Pair p : res) {
out.printLine(p.first + " " + p.second);
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public 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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
a5ea51386bca5cbc5432d958ad57958e
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader jin, PrintWriter jout) {
int n = jin.int32();
int[] currWon1 = new int[n + 1];
int[] currWon2 = new int[n + 1];
int[] timeWon1 = new int[n + 1];
int[] timeWon2 = new int[n + 1];
ArrayUtils.init(timeWon1, Integer.MAX_VALUE);
ArrayUtils.init(timeWon2, Integer.MAX_VALUE);
int totWon1 = 0;
int totWon2 = 0;
boolean lastWon = false;
for(int i = 1; i <= n; i++) {
int t = jin.int32();
currWon1[i] += (t == 1? 1 : 0) + currWon1[i - 1];
currWon2[i] += (t == 2? 1 : 0) + currWon2[i - 1];
if(t == 1) timeWon1[currWon1[i]] = i;
if(t == 2) timeWon2[currWon2[i]] = i;
if(t == 1) totWon1++;
if(t == 2) totWon2++;
lastWon = t == 1;
}
List<Pair> solution = new ArrayList<Pair>();
for(int ti = 1; ti <= n; ti++) {
int cw1 = 0, cw2 = 0;
int sw1 = 0, sw2 = 0;
while(true) {
int nw1 = cw1 + ti;
int nw2 = cw2 + ti;
int t1 = nw1 >= timeWon1.length? Integer.MAX_VALUE: timeWon1[nw1];
int t2 = nw2 >= timeWon2.length? Integer.MAX_VALUE: timeWon2[nw2];
if (t2 < t1) {
sw2++;
cw1 = currWon1[t2];
cw2 = currWon2[t2];
} else if(t2 == t1) {
break;
} else {
sw1++;
cw1 = currWon1[t1];
cw2 = currWon2[t1];
}
}
if(cw1 == totWon1 && cw2 == totWon2) {
if(sw1 > sw2 && lastWon) {
solution.add(new Pair(Math.max(sw1, sw2), ti));
} else if(sw2 > sw1 && !lastWon) {
solution.add(new Pair(Math.max(sw1, sw2), ti));
}
}
}
Collections.sort(solution, new Comparator<Pair>() {
@Override
public int compare(Pair p1, Pair p2) {
return p1.a == p2.a? p1.b - p2.b: p1.a - p2.a;
}
});
jout.println(solution.size());
for(int i = 0; i < solution.size(); i++) {
Pair p = solution.get(i);
jout.println(p.a + " " + p.b);
}
}
}
class Pair {
int a;
int b;
Pair(int aa, int bb) {
a = aa; b = bb;
}
}
class InputReader {
private static final int bufferMaxLength = 1024;
private InputStream in;
private byte[] buffer;
private int currentBufferSize;
private int currentBufferTop;
private static final String tokenizers = " \t\r\f\n";
public InputReader(InputStream stream) {
this.in = stream;
buffer = new byte[bufferMaxLength];
currentBufferSize = 0;
currentBufferTop = 0;
}
private boolean refill() {
try {
this.currentBufferSize = this.in.read(this.buffer);
this.currentBufferTop = 0;
} catch(Exception e) {}
return this.currentBufferSize > 0;
}
public Byte readChar() {
if(currentBufferTop < currentBufferSize) {
return this.buffer[this.currentBufferTop++];
} else {
if(!this.refill()) {
return null;
} else {
return readChar();
}
}
}
public String token() {
StringBuffer tok = new StringBuffer();
Byte first;
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1));
if(first == null) return null;
tok.append((char)first.byteValue());
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) {
tok.append((char)first.byteValue());
}
return tok.toString();
}
public String next() {
return token();
}
public Integer int32() throws NumberFormatException {
String tok = token();
return tok == null? null : Integer.parseInt(tok);
}
}
class ArrayUtils {
public static void init(int[][][] arr, int val) {
for(int[][] subarr: arr)
ArrayUtils.init(subarr, val);
}
public static void init(int[][] arr, int val) {
for(int[] subarr: arr)
ArrayUtils.init(subarr, val);
}
public static void init(int[] arr, int val) {
Arrays.fill(arr, val);
}
public static int accumulate(int[] arr) {
int res = 0;
for(int xx: arr)
res += xx;
return res;
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
d911af0ec426b5d53c2c424f3d229147
|
train_001.jsonl
|
1418833800
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class tennisgame {
private static Reader in;
private static PrintWriter out;
static class Pair implements Comparable<Pair> {
public int a, b;
public Pair (int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return a+" "+b;
}
public int compareTo(Pair other) {
return a == other.a ? b - other.b : a - other.a;
}
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(System.out, true);
N = in.nextInt();
arr = new int[N+1];
psum = new int[N+1];
for (int i = 1; i <= N; i++) {
arr[i] = in.nextInt();
psum[i] = psum[i-1] + (arr[i] == 1 ? 1 : 0);
}
ArrayList<Pair> ans = new ArrayList<Pair>();
for (int i = 1; i <= N; i++) {
int s = getVal(i);
if (s > 0) ans.add(new Pair(s, i));
}
Collections.sort(ans);
out.println(ans.size());
for (Pair p : ans) out.println(p);
out.close();
System.exit(0);
}
public static int[] arr, psum;
public static int N;
public static int getVal (int t) {
int a1 = 0, a2 = 0;
int start = 1;
while (start <= N) {
int lo = start, hi = N;
while (lo < hi) {
int mid = (lo + hi) >> 1;
int k = psum[mid] - psum[start-1];
k = Math.max(k, mid - start + 1 - k);
if (k < t) lo = mid + 1;
else hi = mid;
}
int k = psum[lo] - psum[start-1];
k = Math.max(k, lo - start + 1 - k);
if (k < t) return -1;
if (psum[lo]-psum[start-1] == t) {
a1++;
}
else {
a2++;
}
start = lo + 1;
}
if (a1 == a2) return -1;
int max = Math.max(a1, a2);
a1 = a2 = 0;
start = 1;
while (start <= N) {
int lo = start, hi = N;
while (lo < hi) {
int mid = (lo + hi) >> 1;
int k = psum[mid] - psum[start-1];
k = Math.max(k, mid - start + 1 - k);
if (k < t) lo = mid + 1;
else hi = mid;
}
int k = psum[lo] - psum[start-1];
k = Math.max(k, lo - start + 1 - k);
if (k < t) return -1;
if (psum[lo]-psum[start-1] == t) {
a1++;
}
else {
a2++;
}
start = lo + 1;
if (a2 == max || a1 == max) {
if (start > N) return max;
else return -1;
}
}
return Math.max(a1, a2);
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1024];
int cnt = 0;
byte c = read();
while (c <= ' ')
c = read();
do {
buf[cnt++] = c;
} while ((c = read()) != '\n');
return new String(buf, 0, cnt);
}
public String next() throws IOException {
byte[] buf = new byte[1024];
int cnt = 0;
byte c = read();
while (c <= ' ')
c = read();
do {
buf[cnt++] = c;
} while ((c = read()) > ' ');
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
|
Java
|
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
|
2 seconds
|
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
| null |
Java 7
|
standard input
|
[
"binary search",
"implementation",
"brute force"
] |
eefea51c77b411640a3b92b9f2dd2cf1
|
The first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105). The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
| 1,900 |
In the first line print a single number kΒ β the number of options for numbers s and t. In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.
|
standard output
| |
PASSED
|
8002c0d70c91f62ec45b249ebfee4d0e
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.*;
public class NewYearTransportation{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int t = scan.nextInt();
int from = 0;
int to = 0;
ArrayList<Integer> a = new ArrayList<>();
int counter = 0;
for(int i = 0; i < t-1; i++){
if(i == 0){
from = 1;
to = scan.nextInt()+from;
a.add(to);
counter++;
if(to == t){
System.out.println("YES");
break;
}
}
else{
from = i+1;
to = from + scan.nextInt();
if(a.contains(from)){
a.add(to);
counter++;
if(to == t){
System.out.println("YES");
break;
}
}
///if(a.size() > 1 && a.get(counter-1) - a.get(counter-1-1) > 1){
// System.out.println("NO");
// break;
//}
}
if(i == t-2){
System.out.println("NO");
}
}
//Boolean[][] a = new Boolean[n][n];
//for(int i = 0; i < n-1; i++){
// Arrays.fill(a[i], false);
// a[i][i+scan.nextInt()] = true;
//}
//Arrays.fill(a[n-1], false);
/*
if(a.contains(t)){
System.out.println("YES");
}
else{
System.out.println("NO");
}
*/
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
b0dc877d1ad3408f923b084fb2a95547
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.*;
public class Main {
public static int NN = 30010;
public static Vector[] adj = new Vector[NN];
public static int[] vst = new int[NN];
public static void dfs(int u) {
vst[u]=1;
int n=adj[u].capacity();
for(int i=0; i<n; i++) {
int v=(int)adj[u].elementAt(i);
if(vst[v]==0) dfs(v);
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
for(int i=0; i<NN; i++) {adj[i]=new Vector<Integer>(0); vst[i]=0;}
int n, t;
n=in.nextInt(); t=in.nextInt();
for(int i=1; i<n; i++) {
int x=in.nextInt(), y=i+x;
adj[i].addElement(y);
}
dfs(1);
if(vst[t]==1) System.out.println("YES");
else System.out.println("NO");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
92e7176c3994c8e675313ffc9cf3f150
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt(), t=in.nextInt(), id=1, ok=0;
int[] a=new int[n+1];
for(int i=1; i<n; i++) {
int x=in.nextInt();
if(id==i) id+=x;
if(id==t) ok=1;
}
if(ok==1) System.out.println("YES");
else System.out.println("NO");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
53016156299bb4e434c9fa08646ed4ef
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] s=br.readLine().split(" ");
int n=Integer.parseInt(s[0]);
int t=Integer.parseInt(s[1]);
int[] go=new int[n];
String[] v=br.readLine().split(" ");
for(int i=0;i<n-1;i++){
go[i]=Integer.parseInt(v[i]);
}
String res="NO";
int i=0;
while(i<t){
if(i==(t-1)){
res="YES";
break;
}
if(i==t){
break;
}
i=i+go[i];
}
System.out.println(res);
/*
*/
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
3e6fff31605babbb7393dc7b0bd05766
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.*;
public class Solution{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int t = s.nextInt();
int a[] = new int[n-1];
for(int i=0;i<n-1;i++){
a[i] = s.nextInt();
}
int curIndex = 1;
int done = 0;
while(curIndex<=n){
if(curIndex>t){
break;
}
if(curIndex==t){
done=1;
break;
}
else if(curIndex<t){
curIndex+=a[curIndex-1];
}
}
if(done==1){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
f3ca286b896dfaf1ce05e4058b1e4834
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class NewIO {
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tok;
static boolean hasNext()
{
while(tok==null || !tok.hasMoreTokens())
{
try
{
tok=new StringTokenizer(in.readLine());
}
catch(Exception e)
{
return false;
}
}
return true;
}
static String next()
{
hasNext();
return tok.nextToken();
}
static long nextlong()
{
return Long.parseLong(next());
}
static int nextInt()
{
return Integer.parseInt(next());
}
static PrintWriter out=new PrintWriter (new OutputStreamWriter(System.out));
public static void main(String args[])
{
int n=nextInt();
int t=nextInt();
int a[]=new int [n-1];
for (int i=0 ;i<n-1 ;i++)
{
a[i]=nextInt();
}
int p=1;
for (int i=0 ;i<=t ;i++)
{
p+=a[i];
i+=a[i]-1;
if (p>=t)
{
break;
}
}
if(p==t)
{
out.println("YES");
}
else
{
out.println("NO");
}
out.flush();
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
f311ec4089c83663856725e04807db1c
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Created by rakshit on 7/1/17.
* Java is Love and Code is Beautiful..
*/
public class Qq1 {
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tok;
public InputReader(InputStream inputStream)
{
reader =new BufferedReader(new InputStreamReader(inputStream));
tok=null;
}
public InputReader(String inputFile) throws FileNotFoundException
{
reader=new BufferedReader(new FileReader(inputFile));
tok=null;
}
public String nextLine()
{
String c="";
try
{
c+=reader.readLine();
}
catch(IOException e)
{
throw new RuntimeException(e);
}
return c;
}
public String next()
{
while(tok==null || !tok.hasMoreTokens())
{
try
{
tok=new StringTokenizer(nextLine());
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
return tok.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
}
public static void main(String args[])
{
InputStream inputstream=System.in;
OutputStream outputstream=System.out;
InputReader in=new InputReader(inputstream);
PrintWriter out=new PrintWriter (outputstream);
Task solver=new Task();
solver.solve(in,out);
}
static class Task
{
public void solve(InputReader in , PrintWriter out)
{
int n=in.nextInt();
int t=in.nextInt();
Integer a[]=new Integer[n];
Vector<Pair> check=new Vector();
for(int i=0 ;i<n-1 ;i++)
{
a[i]=in.nextInt();
Pair hello=new Pair();
hello.setp(i+1,i+1+a[i]);
check.add(hello);
}
int i=0,res=0;
for(;i<=t-1;)
{
if(check.elementAt(i).getsec(i+1)==t)
{
res++;
break;
}
else
{
i=check.elementAt(i).getsec(i+1)-1;
}
}
if(res==1)
{
out.println("YES");
}
else
{
out.println("NO");
}
out.flush();
}
}
static class Pair
{
int a;
int b;
public void setp(int a,int b)
{
this.a=a;
this.b=b;
}
public int getsec(int a)
{
return b;
}
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
07aaed4b0273d6052b0d45c43bb5f2f3
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class fivehundredA {
public static void main(String [] som3a)throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String [] ayhaga = bf.readLine().split(" ");
String [] portals = bf.readLine().split(" ");
int index = 0; boolean flag = false;
while(index<Integer.parseInt(ayhaga[1])){
if(index==Integer.parseInt(ayhaga[1])-1){
flag =true; break;}
else
{
index+=Integer.parseInt(portals[index]);
}
}
if (flag)
System.out.print("Yes");
else
System.out.println("No");
}
private static void extracted(Scanner s, int[] portals, int i) {
portals[i]=s.nextInt();
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
5998a05c0d7404714901266c2741591a
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
//package CodeForces;
import java.util.ArrayList;
import java.util.Scanner;
public class NewYearTransport {
// final static int maxn = 3000;
// static boolean [] mark = new boolean[maxn];
// static ArrayList [] graph = new ArrayList[maxn];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), t = sc.nextInt();
int [] Place = new int[n];
for(int i = 0; i<n-1; i++) Place[i] = sc.nextInt();
boolean destination = false;
int i = 0;
while(i < n) {
i += Place[i];
if(i == t-1) {
destination = true;
break;
}
if(Place[i] == 0) break;
}
if(destination == true) System.out.println("Yes");
else System.out.println("No");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
f214c54d8cb64acbd1527d4880557823
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.*;
public class divarr{
public static void main(String s[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int arr[] = new int[n];
for(int i=1;i<n;i++)
arr[i]=sc.nextInt();
boolean b=false;
for(int i=1;i<n;i++){
if(i==m){
b=true;
break;
}
int pos = i+arr[i];
i=pos-1;
if(pos==m){
b=true;
break;
}
}
if(b==false)
System.out.println("NO");
else System.out.println("YES");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
50e45a9c6c2f15f66484827bb1dec414
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.Scanner;
/**
* Created by ΠΠ΅Π½Ρ on 07.03.2017.
*/
public class Task_500A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int all = in.nextInt();
int need = in.nextInt();
int[] a = new int[all];
for (int i = 1; i < all; i++){
a[i] = in.nextInt();
}
int t = a[1] + 1;
int flag = 0;
for (int i = 1; i < all; i++){
while (t <= all){
if(t == need){
flag = 1;
break;
}
if (t == all){
break;
}
t = a[t] + t;
}
}
if (flag == 1){
System.out.println("YES");
}else System.out.println("NO");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
515db47eeb3ab464ac9f343ee5db4685
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int input = in.nextInt();
int t = in.nextInt();
int[] input2 = new int[input ];
for (int i = 0; i < input - 1; i++) {
input2[i] = in.nextInt();
}
int i = 1;
while (i < t)
i += input2[i - 1];
if (i == t)
System.out.println("YES");
else
System.out.println("NO");
in.close();
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
d2c5dd2b3767bb50112ad3b1ddf7f5c7
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.*;
public class Main {
static Reader scan;
static PrintWriter out;
static int cities;
static int destination;
static int[] portals;
public static void main(String[] args) throws IOException {
scan = new Reader();
out = new PrintWriter(System.out, true);
cities = scan.nextInt();
destination = scan.nextInt() - 1;
portals = new int[cities];
for(int i = 0; i < cities - 1; i++) portals[i] = scan.nextInt();
if(findPortal(0)) out.println("YES");
else out.println("NO");
}
public static boolean findPortal(int city){
if (city == destination) return true;
int next = city+portals[city];
if (next <= destination && findPortal(next)) return true;
return false;
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader(){
din=new DataInputStream(System.in);
buffer=new byte[BUFFER_SIZE];
bufferPointer=bytesRead=0;
}
public Reader(String file_name) throws IOException{
din=new DataInputStream(new FileInputStream(file_name));
buffer=new byte[BUFFER_SIZE];
bufferPointer=bytesRead=0;
}
public String readLine() throws IOException{
byte[] buf=new byte[64]; // line length
int cnt=0,c;
while((c=read())!=-1){
if(c=='\n')break;
buf[cnt++]=(byte)c;
}
return new String(buf,0,cnt);
}
public int nextInt() throws IOException{
int ret=0;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c=read();
do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(neg)return -ret;
return ret;
}
public long nextLong() throws IOException{
long ret=0;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c=read();
do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(neg)return -ret;
return ret;
}
public double nextDouble() throws IOException{
double ret=0,div=1;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c = read();
do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(c=='.')while((c=read())>='0'&&c<='9')
ret+=(c-'0')/(div*=10);
if(neg)return -ret;
return ret;
}
private void fillBuffer() throws IOException{
bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);
if(bytesRead==-1)buffer[0]=-1;
}
private byte read() throws IOException{
if(bufferPointer==bytesRead)fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException{
if(din==null) return;
din.close();
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
629698a739383f007d767f78ac9ea60b
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.*;
//http://codeforces.com/problemset/problem/500/A
public class Main {
static Reader scan;
static PrintWriter out;
static int cities;
static int destination;
static int[] portals;
public static void main(String[] args) throws IOException {
scan = new Reader();
out = new PrintWriter(System.out, true);
cities = scan.nextInt();
destination = scan.nextInt() - 1;
portals = new int[cities];
for(int i = 0; i < cities - 1; i++) portals[i] = scan.nextInt();
if(findPortal(0)) out.println("YES");
else out.println("NO");
}
public static boolean findPortal(int city){
if (city == destination) return true;
int next = city+portals[city];
if (next <= destination && findPortal(next)) return true;
return false;
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader(){
din=new DataInputStream(System.in);
buffer=new byte[BUFFER_SIZE];
bufferPointer=bytesRead=0;
}
public Reader(String file_name) throws IOException{
din=new DataInputStream(new FileInputStream(file_name));
buffer=new byte[BUFFER_SIZE];
bufferPointer=bytesRead=0;
}
public String readLine() throws IOException{
byte[] buf=new byte[64]; // line length
int cnt=0,c;
while((c=read())!=-1){
if(c=='\n')break;
buf[cnt++]=(byte)c;
}
return new String(buf,0,cnt);
}
public int nextInt() throws IOException{
int ret=0;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c=read();
do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(neg)return -ret;
return ret;
}
public long nextLong() throws IOException{
long ret=0;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c=read();
do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(neg)return -ret;
return ret;
}
public double nextDouble() throws IOException{
double ret=0,div=1;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c = read();
do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(c=='.')while((c=read())>='0'&&c<='9')
ret+=(c-'0')/(div*=10);
if(neg)return -ret;
return ret;
}
private void fillBuffer() throws IOException{
bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);
if(bytesRead==-1)buffer[0]=-1;
}
private byte read() throws IOException{
if(bufferPointer==bytesRead)fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException{
if(din==null) return;
din.close();
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
dfdcd9ac9223b0bbca0f587d1ade4750
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.*;
public class Main {
static Reader scan;
static PrintWriter out;
static int cities;
static int destination;
static int[] portals;
//static boolean[] visited;
public static void main(String[] args) throws IOException {
scan = new Reader();
out = new PrintWriter(System.out, true);
cities = scan.nextInt();
destination = scan.nextInt() - 1;
portals = new int[cities];
// visited = new boolean[cities];
for(int i = 0; i < cities - 1; i++) portals[i] = scan.nextInt();
// boolean result = false;
// do {
// int nextUnvisited = getNextUnvisited();
// if (nextUnvisited != -1) result = findPortal(nextUnvisited);
// else break;
// } while(result == false);
// boolean result = findPortal(0);
if(findPortal(0)) out.println("YES");
else out.println("NO");
}
// public static int getNextUnvisited(){
// for(int i = 0; i < destination; i++){
// if(visited[i] == false) return i;
// }
// return -1;
// }
public static boolean findPortal(int city){
//visited[city] = true;
if (city == destination) return true;
int next = city+portals[city];
if (next<= destination && findPortal(next)) return true;
return false;
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader(){
din=new DataInputStream(System.in);
buffer=new byte[BUFFER_SIZE];
bufferPointer=bytesRead=0;
}
public Reader(String file_name) throws IOException{
din=new DataInputStream(new FileInputStream(file_name));
buffer=new byte[BUFFER_SIZE];
bufferPointer=bytesRead=0;
}
public String readLine() throws IOException{
byte[] buf=new byte[64]; // line length
int cnt=0,c;
while((c=read())!=-1){
if(c=='\n')break;
buf[cnt++]=(byte)c;
}
return new String(buf,0,cnt);
}
public int nextInt() throws IOException{
int ret=0;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c=read();
do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(neg)return -ret;
return ret;
}
public long nextLong() throws IOException{
long ret=0;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c=read();
do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(neg)return -ret;
return ret;
}
public double nextDouble() throws IOException{
double ret=0,div=1;byte c=read();
while(c<=' ')c=read();
boolean neg=(c=='-');
if(neg)c = read();
do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(c=='.')while((c=read())>='0'&&c<='9')
ret+=(c-'0')/(div*=10);
if(neg)return -ret;
return ret;
}
private void fillBuffer() throws IOException{
bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);
if(bytesRead==-1)buffer[0]=-1;
}
private byte read() throws IOException{
if(bufferPointer==bytesRead)fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException{
if(din==null) return;
din.close();
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
0c5c41ab76b953489a8f6dfadba7dd6f
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class NewYearTransportation {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] temp = br.readLine().split(" ");
int n = Integer.parseInt(temp[0]);
int t = Integer.parseInt(temp[1]);
String[] str_nums = br.readLine().split(" ");
if (str_nums.length != n - 1) {
System.exit(0);
}
boolean flag = false;
int result = 1 + Integer.parseInt(str_nums[0]);
if (result == t) {
flag = true;
System.out.println("YES");
} else {
while (result < n) {
result += Integer.parseInt(str_nums[result - 1]);
if (result == t) {
flag = true;
System.out.println("YES");
break;
}
}
}
if (!flag) {
System.out.println("NO");
}
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
45f222d4879725f99d3a795609b58ec3
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
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 dest = sc.nextInt();
int cells[] = new int[n-1];
for(int i = 0; i < n - 1; i++) {
cells[i] = sc.nextInt();
}
sc.close();
// Starting position
int pos = 1;
// Transport until reach the destination
while(pos < dest) {
pos = pos + cells[pos-1];
}
if(pos == dest)
System.out.println("YES");
else
System.out.println("NO");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
91095775ccb290a54b3e12493e19bf1d
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.Scanner;
public class NewYearTransportation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt()-1;
int num = sc.nextInt()-1;
int[] arr = new int[size];
for(int i = 0;i<size;i++)arr[i]=sc.nextInt();
boolean works = false;
for(int i = 0;i<size;) {
i+=arr[i];
if(i==num) {
works = true;
break;
}
if(i>num)break;
}
System.out.println(works?"YES":"NO");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
828091f3a9c9eff3bfd2ccc93b3fb176
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.util.*;
public class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int x=sc.nextInt();
int a[]=new int[n-1];
for(int i=0;i<n-1;i++)
a[i]=sc.nextInt();
int y;
int i=1;
while(i<n){
y=i+a[i-1];
i=y;
if(y==x)
{System.out.println("YES");System.exit(0);}
}
System.out.println("NO");
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
e9c646773edb2c66e0367ba55c563a96
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.StringTokenizer;
public class F {
public static void main(String[] args) throws IOException {
FastScanner sc=new FastScanner();
// int t = sc.nextInt();
int t = 1;
while(t-- != 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int arr[] = sc.readArray(n-1);
int c = 1;
while(c < m) {
c+=arr[c-1];
}
if(c == m) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
accff8c617ac15933eab1d82fbb06111
|
train_001.jsonl
|
1419951600
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
|
256 megabytes
|
import java.io.*;
import java.util.StringTokenizer;
public class newyear {
public static void main (String[] args) throws IOException {
// BufferedReader reader = new BufferedReader(new FileReader("newyear.in"));
// PrintWriter writer = new PrintWriter(new FileWriter("newyear.out"));
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int m = Integer.parseInt(tokenizer.nextToken());
tokenizer = new StringTokenizer(reader.readLine());
int[] portals = new int[n];
int counter = 0;
while (tokenizer.hasMoreTokens()) {
portals[counter++] = Integer.parseInt(tokenizer.nextToken());
}
int index = 0;
boolean isPossible = false;
for (int i = 0; i < portals.length - 1; i++) {
index += portals[index];
if (index == m - 1) {
isPossible = true;
break;
}
}
if (isPossible) writer.print("YES");
else writer.print("NO");
writer.close();
}
}
|
Java
|
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
|
2 seconds
|
["YES", "NO"]
|
NoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit.
|
Java 8
|
standard input
|
[
"implementation",
"dfs and similar",
"graphs"
] |
9ee3d548f93390db0fc2f72500d9eeb0
|
The first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to. The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
| 1,000 |
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
|
standard output
| |
PASSED
|
e0e2c1afb8b990d9984ee578b8755b90
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
List<Good> main = new ArrayList<Good>();
List<Good> add = new ArrayList<Good>();
for (int i = 0; i < n; ++i) {
int c = in.nextInt();
int t = in.nextInt();
if (t == 1) {
main.add(new Good(c * 2, i + 1));
} else {
add.add(new Good(c * 2, i + 1));
}
}
Collections.sort(main);
Collections.sort(add);
List<Good>[] result = new List[k];
for (int i = 0; i < k; ++i) {
result[i] = new ArrayList<Good>();
}
long res = 0;
if (main.size() >= k) {
for (int i = 0; i < k-1; ++i) {
result[i].add(main.get(i));
res += main.get(i).cost / 2.;
}
for (int i = k-1; i < main.size(); ++i) {
result[k-1].add(main.get(i));
res += main.get(i).cost;
}
for (int i = 0; i < add.size(); ++i) {
result[k-1].add(add.get(i));
res += add.get(i).cost;
}
Collections.sort(result[k-1]);
res -= result[k-1].get(result[k-1].size()-1).cost;
res += result[k-1].get(result[k-1].size()-1).cost / 2;
} else {
for (int i = 0; i < main.size(); ++i) {
result[i].add(main.get(i));
res += main.get(i).cost / 2.;
}
int memo = -1;
for (int i = main.size(); i < k; ++i) {
result[i].add(add.get(i - main.size()));
res += add.get(i - main.size()).cost;
memo = i - main.size();
}
for (int i = memo + 1; i < add.size(); ++i) {
result[k-1].add(add.get(i));
res += add.get(i).cost;
}
}
out.print(res / 2);
if (res % 2 != 0) {
out.println(".5");
} else {
out.println(".0");
}
for (int i = 0; i < k; ++i) {
out.print(result[i].size());
for (Good g : result[i]) {
out.print(" " + g.id);
}
out.println();
}
}
class Good implements Comparable<Good> {
int cost;
int id;
public Good(int cost, int id) {
this.cost = cost;
this.id = id;
}
public int compareTo(Good o) {
return o.cost - cost;
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
031e83addc42c12392b7951542ef4ef9
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), k = sc.nextInt();
Item[] items = new Item[n];
for(int i = 0; i < n; ++i)
items[i] = new Item(sc.nextInt(), sc.nextInt(), i + 1);
Arrays.sort(items);
double ans = 0;
int min = (int)1e9;
ArrayList<Integer>[] carts = new ArrayList[k];
for(int i = 0; i < k; ++i)
carts[i] = new ArrayList<>();
boolean minimize = false;
for(int i = 0, curCart = 0; i < n; ++i)
{
min = Math.min(min, items[i].cost);
if(items[i].type == 1 && curCart < k - 1)
ans += items[i].cost / 2.0;
else
{
minimize |= items[i].type == 1;
ans += items[i].cost;
}
carts[curCart].add(items[i].idx);
if(curCart < k - 1)
curCart++;
}
if(minimize)
ans -= min / 2.0;
out.printf("%.1f\n", ans);
for(int i = 0; i < k; ++i)
{
out.print(carts[i].size());
for(int x: carts[i])
out.print(" " + x);
out.println();
}
out.flush();
out.close();
}
static class Item implements Comparable<Item>
{
int cost, type, idx;
Item(int a, int b, int c) { cost = a; type = b; idx = c; }
public int compareTo(Item i)
{
if(type != i.type)
return type - i.type;
return i.cost - cost;
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
638464a09244d1974c33a416ef1c228b
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.*;
import java.io.*;
// Solution
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
int n = in.nextInt();
int k = in.nextInt();
int ns = 0;
long cost = 0;
long discount = 0;
int minPen = Integer.MAX_VALUE;
Item[] items = new Item[n];
for (int i = 0; i < n; i++) {
int p =in.nextInt();
int type = in.nextInt();
items[i] = new Item(i + 1, p, type);
if (type == STOOL) {
++ns;
}else
minPen = min(minPen, p);
cost += p;
}
Arrays.sort(items);
int s = min(ns, k);
if (ns < k) {
for (int i = 0; i < s; ++i) discount += items[i].price;
}else {
for (int i = 0; i < k - 1; ++i) discount += items[i].price;
discount += min(minPen, items[ns-1].price);
}
int frac = 0;
long d = cost - discount / 2;
if (discount % 2 == 1) {
--d;
frac = 5;
}
System.out.println(d + "." + frac);
if (ns < k) {
for (int i = 0; i < k - 1; i++) System.out.println("1 " + items[i].id);
System.out.print((n - k + 1));
for (int i = k - 1; i < n; i++) System.out.print(" " + items[i].id);
System.out.println();
}else {
for (int i = 0; i < s - 1; i++) System.out.println("1 " + items[i].id);
System.out.print((n - s + 1));
for (int i = s - 1; i < n; i++) System.out.print(" " + items[i].id);
System.out.println();
}
}
private int min(int a, int b) {
return a > b ? b : a;
}
final int STOOL = 1;
final int PEN = 2;
class Item implements Comparable<Item>{
int id, price, type;
public Item(int id, int price, int type) {
this.id = id;
this.price = price;
this.type = type;
}
public int compareTo(Item other) {
if (type != other.type) return type - other.type;
return other.price - price;
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//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)
{
return "";
//e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
b6932d9eb68be40d3178933d00a44381
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
// package CF;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class B {
static int INF = (int)2e9;
static boolean odd;
static long sum;
static void sub(int num){
if((num & 1) != 0)
{
if(odd){
sum--;
}
odd = !odd;
}
sum -= num/2;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), k = sc.nextInt(), minS = INF, minP = INF;
sum = 0L;
PriorityQueue<Point> pq = new PriorityQueue<>(new PriorityQueue<>(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
// TODO Auto-generated method stub
return o2.x - o1.x;
}
}));
Point [] pp = new Point[n];
int [] ans = new int[n];
for (int i = 0; i < n; i++) {
int num = sc.nextInt(), t = sc.nextInt();
pp[i] = new Point(num, t);
if(t == 1){
pq.add(new Point(num, i));
minP = Math.min(minP, num);
}
else{
minS = Math.min(minS, num);
}
sum += num;
}
odd = false;
if(k == 1){
if(!pq.isEmpty()){
sub(Math.min(minS, minP));
}
}
else if(pq.size() < k){
if(pq.size() == 0){
for (int i = 0; i < k-1; i++) {
ans[i] = i+1;
}
}
else{
int cnt = 0;
while(!pq.isEmpty()){
Point tmp = pq.poll();
sub(tmp.x);
ans[tmp.y] = cnt++;
}
for (int j = 0; j < n; j++) {
while(j < n && pp[j].y == 1) j++;
if(j < n)
ans[j] = cnt == k-1?cnt:cnt++;
}
}
}
else{
for (int i = 0; i < k-1; i++) {
Point tmp = pq.poll();
sub(tmp.x);
ans[tmp.y] = i+1;
}
Point p = pq.poll();
int tmp = Math.min(minS, Math.min(p.x, minP));
sub(tmp);
}
if(odd) sum--;
out.println(sum + (odd?".5":".0"));
for (int i = 0; i < k; i++) {
int cnt = 0;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < ans.length; j++) {
if(ans[j] == i)
{
cnt++;
sb.append(" ").append(j+1);
}
}
out.print(cnt);
out.println(sb);
}
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader fileReader) {
br = new BufferedReader(fileReader);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
cd082b0dad27d375cd565a86989c727f
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Solution{
public static Integer INT(String s){
return Integer.parseInt(s);
}
public static Long LONG(String s){
return Long.parseLong(s);
}
//====================================================================================================================
static class Pair implements Comparable<Pair>{
int cost, index;
Pair(int cost, int index){
this.cost=cost;
this.index=index;
}
public int compareTo(Pair obj){
return this.cost-obj.cost;
}
}
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Scanner in=new Scanner(System.in); StringBuilder out=new StringBuilder();
String line[]=br.readLine().split("\\s");
int n=INT(line[0]),
k=INT(line[1]);
ArrayList<Pair> type[]=new ArrayList[3];
for(int i=0; i<=2; i++) type[i]=new ArrayList<>();
for(int i=1; i<=n; i++){
line=br.readLine().split("\\s");
int c=INT(line[0]),
t=INT(line[1]);
type[t].add(new Pair(c, i));
}
Collections.sort(type[1], Collections.reverseOrder());
Collections.sort(type[2]);
int min_cost[]=new int[k], i_1=0, i_2=0;
Arrays.fill(min_cost, -1);
double total_cost=0;
ArrayList<Integer> item[]=new ArrayList[k];
for(int i=0; i<k; i++){
item[i]=new ArrayList<>();
if(i_1!=type[1].size()){
Pair temp=type[1].get(i_1++);
item[i].add(temp.index);
if(i==k-1)
total_cost+=temp.cost;
else
total_cost+=(double)temp.cost/2.0;
min_cost[i]=temp.cost;
}
else{
Pair temp=type[2].get(i_2++);
item[i].add(temp.index);
total_cost+=temp.cost;
}
}
while(i_1!=type[1].size()){
Pair temp=type[1].get(i_1++);
item[k-1].add(temp.index);
total_cost+=temp.cost;
min_cost[k-1]=temp.cost;
}
int i=0, j;
for(j=type[2].size()-1; j>=i_2 && i!=k-1; ){
Pair temp=type[2].get(j);
if(temp.cost>=min_cost[i]){
item[i].add(temp.index);
total_cost+=temp.cost;
j--;
}
else
i++;
}
for(; j>=i_2; j--){
Pair temp=type[2].get(j);
total_cost+=temp.cost;
item[k-1].add(temp.index);
if(min_cost[k-1]!=-1)
min_cost[k-1]=Math.min(min_cost[k-1], temp.cost);
}
if(min_cost[k-1]!=-1)
total_cost-=(double)min_cost[k-1]/2.0;
if((long)total_cost==total_cost)
out.append((long)total_cost+".0");
else
out.append((long)total_cost+".5");
out.append("\n");
for(i=0; i<k; i++){
out.append(item[i].size()+" ");
for(int value: item[i])
out.append(value+" ");
out.append("\n");
}
System.out.print(out);
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
d1087b6ba4a2a3428e4175f5a01fa4b5
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 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);
int n = sc.nextInt();
int k = sc.nextInt();
ArrayList<Item> carts[] = new ArrayList[k];
for (int i = 0; i < k; i++)
carts[i] = new ArrayList<>();
boolean[] discount = new boolean[k];
PriorityQueue<Item> stools = new PriorityQueue<>();
LinkedList<Item> pencils = new LinkedList<>();
for (int i = 0; i < n; i++) {
int cost = sc.nextInt();
int type = sc.nextInt();
if (type == 1) stools.add(new Item(cost, type, i));
else pencils.add(new Item(cost, type, i));
}
Collections.sort(pencils);
for (int i = 0; i < k; i++) {
if (!stools.isEmpty()) {
carts[i].add(stools.remove());
discount[i] = true;
} else carts[i].add(pencils.removeLast());
}
while (!stools.isEmpty())
carts[k - 1].add(stools.remove());
while (!pencils.isEmpty())
carts[k - 1].add(pencils.remove());
double ans = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
sb.append(carts[i].size() + " ");
int min = Integer.MAX_VALUE;
for (Item x : carts[i]) {
ans += x.cost;
sb.append(x.idx + 1 + " ");
min = Math.min(min, x.cost);
}
sb.append("\n");
if (discount[i]) ans -= min / 2.0;
}
out.printf("%.1f\n", ans);
out.println(sb);
out.flush();
out.close();
}
static class Item implements Comparable<Item> {
int cost, type, idx;
public Item(int cost, int type, int idx) {
this.cost = cost;
this.type = type;
this.idx = idx;
}
@Override
public int compareTo(Item o) {
return o.cost - cost;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] ans = new double[n];
for (int i = 0; i < n; i++)
ans[i] = nextDouble();
return ans;
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
c9a59ae703be9117983751f770676ec8
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.*;
public class b161{
static class node {
public int x,y;
node()
{
}
node(int a,int b)
{x=a;
y=b;
}
public int compare(node a,node b)
{
if(a.x>a.y)
return -1;
return 1;
}
}
public static void main(String arg[])
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int[] arr = new int[n];
ArrayList<node> stool = new ArrayList<node>();
ArrayList<node> pen = new ArrayList<node>();
for(int i=0;i<n;i++)
{
int f = sc.nextInt();
int g = sc.nextInt();
arr[i] = f;
if(g==1)
stool.add(new node(f,i));
else
pen.add(new node(f,i));
}
Collections.sort(stool,new Comparator<node>(){
public int compare(node a,node b)
{
if(a.x>b.x)
return -1;
return 1;
}
});
Collections.sort(pen,new Comparator<node>(){
public int compare(node a,node b)
{
if(a.x>b.x)
return -1;
return 1;
}
});
List<Integer>[] ans = (List<Integer>[])new List[k];
for(int f=0;f<k;f++)
ans[f]= new ArrayList<Integer>();
int[] minm = new int[k];
for(int i=0;i<k;i++)
minm[i]=Integer.MAX_VALUE;
int i=0,t=0;
while(t<stool.size())
{
node val = stool.get(t);
ans[i].add(val.y);
if(minm[i]==Integer.MAX_VALUE || val.x<arr[minm[i]])
minm[i]=val.y;
if(i<k-1)
i++;
t++;
}
t=0;
while(t<pen.size())
{
node val = pen.get(t);
ans[i].add(val.y);
if(minm[i]!=Integer.MAX_VALUE && val.x<arr[minm[i]])
minm[i]=val.y;
if(i<k-1)
i++;
t++;
}
double total=0;
//System.out.printf("%.1f\n", total);
for(int l=0;l<k;l++)
{//System.out.print(ans[l].size()+" ");
for(int p=0;p<ans[l].size();p++)
{
if(ans[l].get(p)==minm[l])
{//System.out.print(ans[l].get(p));
total+=((double)arr[ans[l].get(p)]/2);
}
else
total+=(double)(arr[ans[l].get(p)]);
}
//System.out.print((ans[l].get(p)+1)+ " ");
}
System.out.printf("%.1f\n", total);
for(int l=0;l<k;l++)
{System.out.print(ans[l].size()+" ");
for(int p=0;p<ans[l].size();p++)
{
System.out.print((ans[l].get(p)+1)+" ");
}
//System.out.print((ans[l].get(p)+1)+ " ");
System.out.println();
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
90662a8cdf9359bcef6a8c0dac9ad35c
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
public class CF_Discounts {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
PriorityQueue<Item> stools = new PriorityQueue<>();
Queue<Item> pencils = new LinkedList<>();
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int p = sc.nextInt();
int t = sc.nextInt();
Item it = new Item(p, i + 1);
if (t == 1)
stools.add(it);
else
pencils.add(it);
min = Math.min(min, p);
}
double total = 0;
StringBuilder out = new StringBuilder();
while (k-- > 0) {
if (k == 0) {
out.append("\n" + (stools.size() + pencils.size()));
if (stools.size() != 0)
total -= min / 2.0;
while (stools.size() != 0) {
Item it = stools.poll();
total += it.p;
out.append(" " + it.idx);
}
while (pencils.size() != 0) {
Item it = pencils.poll();
total += it.p;
out.append(" " + it.idx);
}
} else {
out.append("\n1 ");
if (stools.size() != 0) {
Item it = stools.poll();
total += it.p / 2.0;
out.append(it.idx);
} else {
Item it = pencils.poll();
total += it.p;
out.append(it.idx);
}
}
}
System.out.printf("%.1f", total);
System.out.println(out);
}
static class Item implements Comparable<Item> {
int p;
int idx;
public Item(int a, int b) {
p = a;
idx = b;
}
public int compareTo(Item o) {
return o.p - p;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String f) throws FileNotFoundException {
br = new BufferedReader(new FileReader(f));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArray1(int n) throws IOException {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextInt();
return a;
}
public int[] shuffle(int[] a, int n) {
int[] b = new int[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
int t = b[i];
b[i] = b[j];
b[j] = t;
}
return b;
}
public int[] nextIntArraySorted(int n) throws IOException {
int[] a = nextIntArray(n);
a = shuffle(a, n);
Arrays.sort(a);
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArray1(int n) throws IOException {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArraySorted(int n) throws IOException {
long[] a = nextLongArray(n);
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
return a;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
883933a2c44071a258e5384d03949447
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class Discounts_CF161B {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int carts = sc.nextInt();
ArrayList<Item> stools = new ArrayList<Item>();
ArrayList<Item> pencils = new ArrayList<Item>();
int min[] = new int[carts];
Arrays.fill(min, ((int) 1e9 + 1));
boolean hasStool[] = new boolean[carts];
ArrayList<Integer> cart[] = new ArrayList[carts];
for (int i = 0; i < carts; i++)
cart[i] = new ArrayList<Integer>();
double total = 0;
for (int i = 0; i < n; i++) {
int c = sc.nextInt();
total += c;
if (sc.nextInt() == 1)
stools.add(new Item(i, -1 * c));
else
pencils.add(new Item(i, c));
}
Collections.sort(stools);
Collections.sort(pencils);
int curr = 0;
for (Item stool : stools) {
min[curr] = stool.cost * -1;
hasStool[curr] = true;
cart[curr].add(stool.ind + 1);
curr = Math.min(curr + 1, carts - 1);
}
curr = carts - 1;
for (Item pen : pencils) {
while (curr != 0 && min[curr] != (int) (1e9 + 1)
&& (min[curr - 1] == (int) (1e9 + 1) || min[curr - 1] < pen.cost))
curr--;
min[curr] = Math.min(min[curr], pen.cost);
cart[curr].add(pen.ind + 1);
}
for (int i = 0; i < carts; i++)
if (hasStool[i])
total -= min[i] / 2.0;
long tot = (long)(total);
out.println(tot == total ? tot + ".0": tot + ".5");
for(int i = 0; i < carts; i++){
out.print(cart[i].size());
for(int ind:cart[i])
out.print(" " + ind);
out.println();
}
out.flush();
out.close();
}
static class Item implements Comparable<Item> {
int ind;
int cost;
public Item(int ind, int cost) {
this.ind = ind;
this.cost = cost;
}
public int compareTo(Item o) {
return cost == o.cost ? ind - o.ind : cost - o.cost;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
9347ffaf4563ea4f75507e0e4e79299c
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.*;
public class Discounts {
public static void main(String args[]) throws Exception {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int k = cin.nextInt();
int[] t = new int[2001];
int[] c = new int[2001];
int[] ind = new int[2001];
int[] kol = new int[2001];
int[] min = new int[2001];
int[] ll = new int[2001];
boolean[] use = new boolean[2001];
int[][] a = new int[2001][2001];
for (int i = 1; i <= n; i++) {
c[i] = cin.nextInt();
t[i] = cin.nextInt();
ind[i] = i;
}
cin.close();
for (int i = 1; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
if (c[i] < c[j]) {
int yed = c[i];
c[i] = c[j];
c[j] = yed;
yed = ind[i];
ind[i] = ind[j];
ind[j] = yed;
yed = t[i];
t[i] = t[j];
t[j] = yed;
}
}
}
int j = 0;
for (int i = 1; i <= n; i++) {
if (t[i] == 1) {
if (j < k)
j++;
kol[j]++;
a[j][kol[j]] = ind[i];
use[j] = true;
if (c[i] < min[j] || min[j] == 0) {
min[j] = c[i];
}
ll[i] = j;
}
}
for (int i = 1; i <= n; i++) {
if (t[i] == 2) {
if (j < k)
j++;
kol[j]++;
a[j][kol[j]] = ind[i];
if (c[i] < min[j] || min[j] == 0) {
min[j] = c[i];
}
ll[i] = j;
}
}
double ans = 0;
for (int i = 1; i <= k; i++) {
if (min[i] > 0) {
if (use[i]) {
ans += (double) min[i] * 0.5;
} else {
ans += min[i];
}
}
}
boolean[] b = new boolean[20001];
for (int i = 1; i <= n; i++) {
if (c[i] != min[ll[i]] || b[ll[i]]) {
ans += c[i];
} else if (c[i] == min[ll[i]]) {
b[ll[i]] = true;
}
}
System.out.printf("%.1f\n", ans);
for (int i = 1; i <= k; i++) {
System.out.print(kol[i]);
for (j = 1; j <= kol[i]; j++) {
System.out.print(" " + a[i][j]);
}
System.out.println();
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
8198c82239e639fe6f00cc0a8cbe50cb
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.Writer;
import java.util.Collections;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Comparator;
import java.io.PrintWriter;
import java.util.Locale;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.io.OutputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Alex
*/
public class Main{
public static void main(String[] args){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB{
public void solve(int testNumber, InputReader in, OutputWriter out){
int numitems = in.ri(), numcarts = in.ri();
ArrayList<Item> stools = new ArrayList<>(), pencils = new ArrayList<>();
for(int i = 0; i < numitems; i++) {
int cost = in.ri(), type = in.ri();
Item item = new Item(type, cost, i);
if(type == 1) stools.add(item);
else pencils.add(item);
}
int numstools = stools.size(), numpencils = pencils.size();
Collections.sort(stools, Comparator.comparing((Item i) -> i.price));
// Collections.sort(pencils, Comparator.comparing((Item i) -> i.price));
ArrayList<Item>[] res = new ArrayList[numcarts];
for(int i = 0; i < res.length; i++) res[i] = new ArrayList<>();
for(int i = 0; i < numcarts; i++) {
if(!stools.isEmpty()){
Item stool = stools.remove(stools.size() - 1);
res[i].add(stool);
}
}
for(int i = Math.min(numstools, numcarts - 1); i < numcarts; i++) {
if(!pencils.isEmpty()){
Item pencil = pencils.remove(pencils.size() - 1);
res[i].add(pencil);
}
}
while(!pencils.isEmpty()) res[numcarts - 1].add(pencils.remove(pencils.size() - 1));
while(!stools.isEmpty()) res[numcarts - 1].add(stools.remove(stools.size() - 1));
double ans = 0;
for(ArrayList<Item> items : res) {
double total = 0;
int cheapest = Integer.MAX_VALUE;
for(Item item : items) {
total += item.price;
cheapest = Math.min(cheapest, item.price);
}
if(items.get(0).type == 1){
total -= (double) cheapest / 2;
}
ans += total;
}
out.printLineDouble(ans);
for(ArrayList<Item> items : res) {
out.print(items.size() + " ");
for(Item item : items) {
out.print((item.index + 1) + " ");
}
out.printLine();
}
// double totalcost = 0;
// ArrayList<Integer> stoolindexes = new ArrayList<>();
// ArrayList<IntPair> pencils = new ArrayList<>(); // cost, index
// for(int item = 0; item < numitems; item++) {
// int cost = in.ri(), type = in.ri();
// if (type == 1){
// stoolindexes.add(item);
// totalcost += cost;
// }
// else{
// pencils.add(new IntPair(cost, item));
// }
// }
// Collections.sort(pencils, Comparator.comparing((IntPair p) -> -p.first));
// ArrayList<Integer>[] res = new ArrayList[numcarts];
// for(int i = 0; i < numcarts; i++) res[i] = new ArrayList<>();
// for(int i = 0; i < stoolindexes.size(); i++) {
// res[i % numcarts].add(stoolindexes.get(i));
// }
// for(int i = 0; i < pencils.size(); i++) {
// int index = Math.min(i, numcarts - 1);
// res[index].add(pencils.get(i).second);
// double cost = pencils.get(i).first;
// if ((i < numcarts - 1 && i < stoolindexes.size()) || (i == numcarts - 1 && i == pencils.size() - 1)) totalcost += cost / 2;
// else totalcost += cost;
// }
// out.printLine(totalcost);
}
class Item{
int type;
int price;
int index;
public Item(int type, int price, int index){this.type = type; this.price = price; this.index = index;}
}
}
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(){
writer.println();
}
public void printLineDouble(double d){ //slow
DecimalFormat df = new DecimalFormat("0.0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
writer.println(df.format(d));
}
public void close(){
writer.close();
}
}
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 ri(){
return readInt();
}
public int readInt(){
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-'){
sgn = -1;
c = read();
}
int res = 0;
do{
if(c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c){
if(filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c){
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
f4b3adb38b14ec8363bdff436b39c6b4
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.Writer;
import java.util.Collections;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Comparator;
import java.io.PrintWriter;
import java.util.Locale;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.io.OutputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Alex
*/
public class Main{
public static void main(String[] args){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB{
public void solve(int testNumber, InputReader in, OutputWriter out){
int numitems = in.ri(), numcarts = in.ri();
ArrayList<Item> stools = new ArrayList<>(), pencils = new ArrayList<>();
for(int i = 0; i < numitems; i++) {
int cost = in.ri(), type = in.ri();
Item item = new Item(type, cost, i);
if(type == 1) stools.add(item);
else pencils.add(item);
}
int numstools = stools.size(), numpencils = pencils.size();
Collections.sort(stools, Comparator.comparing((Item i) -> i.price));
// Collections.sort(pencils, Comparator.comparing((Item i) -> i.price));
ArrayList<Item>[] res = new ArrayList[numcarts];
for(int i = 0; i < res.length; i++) res[i] = new ArrayList<>();
for(int i = 0; i < numcarts; i++) {
if(!stools.isEmpty()){
Item stool = stools.remove(stools.size() - 1);
res[i].add(stool);
}
}
for(int i = Math.min(numstools, numcarts - 1); i < numcarts; i++) {
if(!pencils.isEmpty()){
Item pencil = pencils.remove(pencils.size() - 1);
res[i].add(pencil);
}
}
while(!pencils.isEmpty()) res[numcarts - 1].add(pencils.remove(pencils.size() - 1));
while(!stools.isEmpty()) res[numcarts - 1].add(stools.remove(stools.size() - 1));
double ans = 0;
for(ArrayList<Item> items : res) {
double total = 0;
int cheapest = Integer.MAX_VALUE;
for(Item item : items) {
total += item.price;
cheapest = Math.min(cheapest, item.price);
}
if(items.get(0).type == 1){
total -= (double) cheapest / 2;
}
ans += total;
}
DecimalFormat df = new DecimalFormat("0.0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
out.printLine(df.format(ans));
for(ArrayList<Item> items : res) {
out.print(items.size() + " ");
for(Item item : items) {
out.print((item.index + 1) + " ");
}
out.printLine();
}
// double totalcost = 0;
// ArrayList<Integer> stoolindexes = new ArrayList<>();
// ArrayList<IntPair> pencils = new ArrayList<>(); // cost, index
// for(int item = 0; item < numitems; item++) {
// int cost = in.ri(), type = in.ri();
// if (type == 1){
// stoolindexes.add(item);
// totalcost += cost;
// }
// else{
// pencils.add(new IntPair(cost, item));
// }
// }
// Collections.sort(pencils, Comparator.comparing((IntPair p) -> -p.first));
// ArrayList<Integer>[] res = new ArrayList[numcarts];
// for(int i = 0; i < numcarts; i++) res[i] = new ArrayList<>();
// for(int i = 0; i < stoolindexes.size(); i++) {
// res[i % numcarts].add(stoolindexes.get(i));
// }
// for(int i = 0; i < pencils.size(); i++) {
// int index = Math.min(i, numcarts - 1);
// res[index].add(pencils.get(i).second);
// double cost = pencils.get(i).first;
// if ((i < numcarts - 1 && i < stoolindexes.size()) || (i == numcarts - 1 && i == pencils.size() - 1)) totalcost += cost / 2;
// else totalcost += cost;
// }
// out.printLine(totalcost);
}
class Item{
int type;
int price;
int index;
public Item(int type, int price, int index){this.type = type; this.price = price; this.index = index;}
}
}
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(){
writer.println();
}
public void printLine(Object... objects){
print(objects);
writer.println();
}
public void close(){
writer.close();
}
}
static class InputReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream){
this.stream = stream;
}
public int read(){
if(numChars == -1)
throw new InputMismatchException();
if(curChar >= numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch(IOException e){
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ri(){
return readInt();
}
public int readInt(){
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-'){
sgn = -1;
c = read();
}
int res = 0;
do{
if(c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c){
if(filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c){
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
433b6c77f64fdb3f0ad8d158cd0598a6
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.*;
import java.util.stream.Collectors;
import java.io.*;
public class Discounts {
/************************ SOLUTION STARTS HERE ************************/
static class Item {
int idx , cost , type;
Item (int... arg) {
idx = arg[0];
cost = arg[1];
type = arg[2];
}
}
@SuppressWarnings("unchecked")
private static void solve() {
int n = nextInt();
int k = nextInt();
ArrayList<Integer>[] cart = new ArrayList[k];
for(int i = 0; i < k; i++)
cart[i] = new ArrayList<>();
Item arr[] = new Item[n];
for(int i = 0; i < n; i++)
arr[i] = new Item(i , nextInt() , nextInt());
List<Integer> stools = Arrays.stream(arr).
filter(item -> item.type == 1).
map(item -> item.idx).
collect(Collectors.toList());
stools.sort((id1 , id2) -> Integer.compare(arr[id2].cost, arr[id1].cost));
int curr = Math.min(k - 1 , stools.size());
boolean marked[] = new boolean[n];
long discounted = 0;
for(int i = 0; i < curr; i++) {
discounted += arr[stools.get(i)].cost;
marked[stools.get(i)] = true;
cart[i].add(stools.get(i) + 1);
}
if(stools.size() >= k)
discounted += Arrays.stream(arr).min(new Comparator<Item>() {
public int compare(Item o1, Item o2) {
return o1.cost - o2.cost;
};
}).get().cost;
else {
int last = 0;
for(; curr < k - 1; curr++) {
for(; last < n; last++)
if(!marked[last]) {
marked[last] = true;
cart[curr].add(last + 1);
break;
}
}
}
for(int i = 0; i < n; i++)
if(!marked[i])
cart[curr].add(i + 1);
long total = (2L * Arrays.stream(arr).mapToLong(it -> it.cost).sum()) - discounted;
println(String.format("%d.%d", total / 2 , 5 * (total % 2)));
Arrays.stream(cart).forEach(c -> {
print(c.size() + " ");
c.stream().forEach(index -> print(index + " "));
print('\n');
});
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE **********************/
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
st = null;
solve();
reader.close();
writer.close();
}
static BufferedReader reader;
static PrintWriter writer;
static StringTokenizer st;
static String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
static int nextInt() {return Integer.parseInt(next());}
static long nextLong() {return Long.parseLong(next());}
static double nextDouble(){return Double.parseDouble(next());}
static char nextChar() {return next().charAt(0);}
static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;}
static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;}
static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;}
static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;}
static void print(Object o) { writer.print(o); }
static void println(Object o){ writer.println(o);}
/************************ TEMPLATE ENDS HERE ************************/
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
e52c13d8e5ece2b1c14103a06219dbed
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
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.util.*;
import java.io.*;
public class codeforces
{
static class Student{
int x,y;//z;
Student(int x,int y){
this.x=x;
this.y=y;
//this.z=z;
}
}
static int prime[];
static void sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
int pos=0;
prime= new int[n+1];
for(int p = 2; p*p <=n; p++)
{
// If prime[p] is not changed, then it is a prime
if(prime[p] == 0)
{
// Update all multiples of p
prime[p]=p;
for(int i = p*p; i <= n; i += p)
if(prime[i]==0)
prime[i] = p;
}
}
}
static class Sortbyroll implements Comparator<Student>
{
// Used for sorting in ascending order of
// roll number
public int compare(Student c, Student b)
{
return b.x-c.x;
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static class Edge{
int a,b;
Edge(int a,int b){
this.a=a;
this.b=b;
}
}
static class Trie{
HashMap<Character,Trie>map;
int c;
Trie(){
map=new HashMap<>();
//z=null;
//o=null;
c=0;
}
}
//static long ans;
static int parent[];
static int rank[];
// static int b[][];
static int bo[][];
static int ho[][];
static int seg[];
//static int pos;
// static long mod=1000000007;
//static int dp[][];
static HashMap<String,Integer>map;
static PriorityQueue<Student>q=new PriorityQueue<>();
//static Stack<Integer>st;
// static ArrayList<Character>ans;
static ArrayList<ArrayList<Integer>>adj;
//static long ans;
static int pos;
static Trie root;
static long fac[];
static int gw,gb;
static long mod=(long)(998244353);
static int ans;
static void solve()throws IOException{
FastReader sc=new FastReader();
int n,k,x,y,i,min;
double ans=0.0;
StringBuilder sb=new StringBuilder();
ArrayList<Student>a=new ArrayList<>();
ArrayList<Student>b=new ArrayList<>();
n=sc.nextInt();
k=sc.nextInt();
for(i=0;i<n;i++){
x=sc.nextInt();
y=sc.nextInt();
if(y==1)
a.add(new Student(x,i+1));
else
b.add(new Student(x,i+1));
}
Collections.sort(a,new Sortbyroll());
if(a.size()>=k){
for(i=0;i<k-1;i++){
ans+=(double)(a.get(i).x)/2.0;
sb.append(1+" "+a.get(i).y+"\n");
}
min=Integer.MAX_VALUE;
sb.append((n-k+1));
for(i=k-1;i<a.size();i++){
min=Math.min(min,a.get(i).x);
ans+=(double)a.get(i).x;
sb.append(" "+a.get(i).y);
}
for(i=0;i<b.size();i++){
min=Math.min(min,b.get(i).x);
ans+=(double)b.get(i).x;
sb.append(" "+b.get(i).y);
}
ans-=(double)min/2.0;
}
else{
// System.out.println("yes");
for(i=0;i<a.size();i++){
ans+=(double)a.get(i).x/2.0;
sb.append(1+" "+a.get(i).y+"\n");
}
for(i=0;i<k-a.size()-1;i++){
ans+=(double)b.get(i).x;
sb.append(1+" "+b.get(i).y+"\n");
}
sb.append(n-a.size()-i);
while(i<b.size()){
ans+=(double)b.get(i).x;
sb.append(" "+b.get(i).y);
++i;
}
}
System.out.printf("%.1f\n", ans);
System.out.println(sb.toString());
}
static boolean isSafe(int x,int y,int b[][],String s[] ){
if(x>=0&&x<b.length&&y>=0&&y<b[0].length&&s[x].charAt(y)=='#'&&b[x][y]==0)
return true;
return false;
}
static void add(int x,int y,Queue<Integer>q,Queue<Integer>v,int b[][]){
q.add(x);
v.add(y);
b[x][y]=1;
}
static long nCr(long n, long r,
long p)
{
return (fac[(int)n]* modInverse(fac[(int)r], p)
% p * modInverse(fac[(int)(n-r)], p)
% p) % p;
}
//static int prime[];
//static int dp[];
public static void main(String[] args){
//long sum=0;
try {
codeforces.solve();
} catch (Exception e) {
e.printStackTrace();
}
}
static long modInverse(long n, long p)
{
return power(n, p-(long)2,p);
}
static long power(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y %(long)2!=0)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res%p;
}
/*public static long power(long x,long a) {
if(a==0) return 1;
if(a%2==1)return (x*1L*power(x,a-1))%mod;
return (power((int)((x*1L*x)%mod),a/2))%mod;
}*/
static int find(int x)
{
// Finds the representative of the set
// that x is an element of
while(parent[x]!=x)
{
// if x is not the parent of itself
// Then x is not the representative of
// his set,
x=parent[x];
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return x;
}
static void union(int x, int y)
{
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
static long gcd(long a, long b)
{
if (a == 0){
//ans+=b;
return b;
}
return gcd(b % a, a);
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
2a8d252465e2817fb49f8d11bad0f743
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.text.*;
public class Main {
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception{}
void solve(int TC) throws Exception {
int N = ni(), K = ni();
long[][] P = new long[N][2];
for(int i = 0; i< N; i++)P[i] = new long[]{nl(), nl(), i+1};
Arrays.sort(P, (long[] l1, long[] l2) -> {
if(l1[1] != l2[1])return Long.compare(l1[1], l2[1]);
return Long.compare(l2[0], l1[0]);
});
double ans = 0;
for(int i = 0; i< K-1; i++){
if(P[i][1] == 1)ans += P[i][0]/2.0;
else ans += P[i][0];
}
for(int i = K-1; i< N; i++)ans += P[i][0];
if(P[K-1][1] == 1){
long mn = P[K-1][0];
for(int i = K-1; i< N; i++)mn = Math.min(mn, P[i][0]);
ans -= mn/2.0;
}
pn((new DecimalFormat(("0.0"))).format(ans));//df.format(ans));
for(int i = 0; i< K-1; i++){
pn("1 "+P[i][2]);
}
p((N-K+1));
for(int i = K-1; i< N; i++)p(" "+(P[i][2]));pn("");
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
static void debug(Object... o){System.err.println(Arrays.deepToString(o));}
final long IINF = (long)2e18;
final int INF = (int)1e9+2;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
static boolean multipleTC = false, memory = true, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = multipleTC? ni():1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println(System.currentTimeMillis() - ct);
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
int[][] make(int n, int e, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1};
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
d77e07d19a73ea40de3c6e79e6171137
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.*;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* Created by wencan on 2015/6/9.
*/
public class Discounts {
public static void main(String[] args) throws IOException {
Discounts discounts = new Discounts();
discounts.resolve();
}
private void resolve() throws IOException {
Reader reader = new Reader(System.in);
int n = reader.nextInt();
int k = reader.nextInt();
int kcopy = k;
PriorityQueue<Data> a = new PriorityQueue<Data>(n, orderComparator);
PriorityQueue<Data> b = new PriorityQueue<Data>(n, orderComparator);
int next;
int[] value = new int[n+1];
for (int i = 1; i <= n; i++) {
next = reader.nextInt();
if(reader.nextInt()==1) a.add(new Data(next, i));
else b.add(new Data(next, i));
value[i] = next;
}
int aini = a.size();
int diff = 0;
int[] c = new int[b.size()];
if (aini >= k) {
b.add(a.poll());
while (a.size() > k - 1) {
b.add(a.poll());
}
}
else {
diff = k - aini - 1;
for (int i = 0; i < diff; i++) {
c[i] = b.poll().index;
}
}
double sum = 0.0;
int[] first = new int[b.size()];
first[0] = b.peek().index;
if(aini>=k) sum += b.poll().value / 2.0;
else sum += b.poll().value;
for (int i = 1; i < first.length; i++) {
first[i] = b.peek().index;
sum += b.poll().value;
}
int[] other = new int[a.size()];
for (int i = 0; i < other.length; i++) {
sum += a.peek().value / 2.0;
other[i] = a.poll().index;
}
for (int i = 0; i < diff; i++) {
sum += value[c[i]];
}
System.out.println(String.format("%.1f", sum));
if (first.length > 0) {
System.out.print(first.length+" ");
for (int i = 0; i < first.length-1; i++) {
System.out.print(first[i] + " ");
}
System.out.println(first[first.length-1]);
}
for (int anOther : other) System.out.println("1 " + anOther);
for (int i = 0; i < diff; i++) {
System.out.println("1 "+ c[i]);
}
}
private class Data {
int value;
int index;
public Data(int value, int index) {
this.value = value;
this.index = index;
}
}
Comparator<Data> orderComparator = new Comparator<Data>() {
public int compare(Data o1, Data o2) {
return o1.value - o2.value;
}
};
private class Reader {
StreamTokenizer tokenizer;
public Reader(InputStream inputStream) {
tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(inputStream)));
}
public int nextInt() throws IOException {
tokenizer.nextToken();
return (int) tokenizer.nval;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
284dfefa4c72b7c2fafcf763fb64f3c5
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static final long MOD = 1000000007L;
static final int INF = 50000000;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int N = sc.ni();
int K = sc.ni();
ArrayList<Pair> type[]=new ArrayList[3];
for(int i=0; i < 3; i++)
type[i]=new ArrayList<Pair>();
for(int i = 0; i < N; i++) {
int a = sc.ni();
int b = sc.ni();
type[b].add(new Pair(a,i));
}
Collections.sort(type[1], Collections.reverseOrder());
Collections.sort(type[2]);
int[] min_cost=new int[K];
int i_1=0;
int i_2=0;
Arrays.fill(min_cost, -1);
double total_cost=0;
ArrayList<Integer>[] item = new ArrayList[K];
for(int i=0; i < K; i++){
item[i]=new ArrayList<>();
if(i_1!=type[1].size()){
Pair temp=type[1].get(i_1);
i_1++;
item[i].add(temp.index);
if(i==K-1)
total_cost+=temp.cost;
else
total_cost+=(double)temp.cost/2.0;
min_cost[i]=temp.cost;
}
else{
Pair temp=type[2].get(i_2);
i_2++;
item[i].add(temp.index);
total_cost+=temp.cost;
}
}
while(i_1!=type[1].size()){
Pair temp=type[1].get(i_1++);
item[K-1].add(temp.index);
total_cost+=temp.cost;
min_cost[K-1]=temp.cost;
}
int i=0, j;
for(j=type[2].size()-1; j>=i_2 && i!=K-1; ){
Pair temp=type[2].get(j);
if(temp.cost>=min_cost[i]){
item[i].add(temp.index);
total_cost+=temp.cost;
j--;
}
else
i++;
}
for(; j>=i_2; j--){
Pair temp=type[2].get(j);
total_cost+=temp.cost;
item[K-1].add(temp.index);
if(min_cost[K-1]!=-1)
min_cost[K-1]=Math.min(min_cost[K-1], temp.cost);
}
if(min_cost[K-1]!=-1)
total_cost-=(double)min_cost[K-1]/2.0;
if((long)total_cost==total_cost)
pw.println((long)total_cost+".0");
else
pw.println((long)total_cost+".5");
for(i=0; i< K; i++){
pw.print(item[i].size()+" ");
for(int value: item[i])
pw.print((value+1)+" ");
pw.println();
}
pw.close();
}
static class Pair implements Comparable<Pair>{
int cost, index;
Pair(int cost, int index){
this.cost=cost;
this.index=index;
}
public int compareTo(Pair obj){
return this.cost-obj.cost;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
83e97103728c232bfe94710ae9e1fd20
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class templ {
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
int partition(int arr[],int a[],int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
if (arr[j] <= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
temp = a[i+1];
a[i+1] = a[high];
a[high] = temp;
return i+1;
}
void sort(int arr[],int a[],int low, int high)
{
if (low < high)
{
int pi = partition(arr,a,low, high);
sort(arr,a,low,pi-1);
sort(arr,a,pi+1, high);
}
}
public static void main(String[] args) throws FileNotFoundException {
try
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
templ ob=new templ();
int n=in.nextInt();
int k=in.nextInt();
int cost1[]=new int[n];
int pos1[]=new int[n];
int cost2[]=new int[n];
int pos2[]=new int[n];
int x1=0,x2=0;
long sum=0;
for(int i=0;i<n;i++)
{
int x=in.nextInt();
int type=in.nextInt();
if(type==1)
{
cost1[x1]=x;
pos1[x1]=i+1;
x1++;
}
else
{
cost2[x2]=x;
pos2[x2]=i+1;
x2++;
}
sum+=x;
}
ob.sort(cost1,pos1,0,x1-1);
ob.sort(cost2,pos2,0,x2-1);
double dis=0;
int xx1=x1;
int xx2=x2;
int kk=k;
while(k!=0)
{
if(k>1&&x1!=0)
{
int x=cost1[x1-1];
dis+=(double)x/2;
x1--;
}
else if(k==1&&x1!=0)
{
int x;
if(x2!=0)
x=Math.min(cost1[0],cost2[0]);
else
x=cost1[0];
dis+=(double)x/2;
}
k--;
}
k=kk;
x1=xx1;
x2=xx2;
long d=(long)Math.ceil(dis);
long cost=sum-d;
out.print(cost);
if(dis!=Math.ceil(dis))
out.println(".5");
else
out.println(".0");
while(k!=0)
{
if(k>1&&x1!=0)
{
out.print("1 "+pos1[x1-1]);
x1--;
k--;
out.println();
}
else if(k>1&&x1==0)
{
out.print("1 "+pos2[x2-1]);
x2--;
k--;
out.println();
}
else if(k==1)
{
int p=x1+x2;
out.print(p+" ");
for(int i=0;i<x1;i++)
out.print(pos1[i]+" ");
for(int i=0;i<x2;i++)
out.print(pos2[i]+" ");
out.println();
k--;
}
}
out.close();
}
catch(Exception e){
return;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
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 nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 8
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
9f414e0c281057f4ff9fb62114ba78dd
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import javax.print.attribute.HashAttributeSet;
public class CodeForces {
public void solve() throws IOException {
int n = nextInt();
int k = nextInt();
List<Res> ths = new ArrayList<Res>();
int tCount = 0;
for (int i = 0, l = n; i < l; i++) {
int p = nextInt();
int t = nextInt();
if (t == 1)
tCount++;
ths.add(new Res((i + 1), p, t));
}
List<List<Res>> ans = new ArrayList<List<Res>>();
for (int i = 0, l = k; i < l; i++) {
ans.add(new ArrayList<CodeForces.Res>());
}
Collections.sort(ths, new Comparator<Res>() {
public int compare(Res o1, Res o2) {
if (o1.price > o2.price) {
return 1;
} else if (o1.price < o2.price) {
return -1;
} else {
return 0;
}
}
});
int curBusk = 0;
double price = 0.0;
while (!ths.isEmpty()) {
if (ths.size() == k - curBusk) {
for (Res t : ths) {
ans.get(curBusk).add(t);
if (t.type == 1) {
price += t.price / 2.0;
} else {
price += t.price;
}
curBusk++;
}
ths.clear();
} else {
if (curBusk != k-1) {
double tPrice = 0;
Res o = ths.remove(ths.size() - 1);
tPrice += o.price;
if (o.type == 1) {
tPrice = tPrice / 2.0;
tCount--;
}
ans.get(curBusk).add(o);
if (o.type != 1 && tCount > 0) {
for (int i = ths.size() - 1; i > -1; i--) {
if (ths.get(i).type == 1) {
Res to = ths.remove(i);
tPrice = tPrice + to.price / 2.0;
ans.get(curBusk).add(to);
tCount--;
break;
}
}
}
price += tPrice;
curBusk++;
} else {
ans.get(curBusk).addAll(ths);
if(tCount>0){
price += ths.remove(0).price/2.0;
}
for (Res t : ths) {
price += t.price;
}
ths.clear();
}
}
}
NumberFormat formatter = new DecimalFormat("0.0");
out.println( formatter.format(price));
for (List<Res> ls : ans) {
StringBuffer sb = new StringBuffer();
sb.append(ls.size());
for (Res t : ls) {
sb.append(" ").append(t.counter);
}
out.println(sb.toString());
}
}
private class Res {
int counter;
int price;
int type;
public Res(int counter, int price, int type) {
this.counter = counter;
this.price = price;
this.type = type;
}
}
private boolean isPal(String s) {
boolean retValue = true;
for (int i = 0, l = s.length() / 2; i < l; i++) {
if (s.charAt(i) != s.charAt(s.length() - i - 1)) {
retValue = false;
break;
}
}
return retValue;
}
public static void main(String[] args) {
new CodeForces().run();
}
long NOD(long a, long b) {
while (a != 0 && b != 0) {
if (a >= b)
a = a % b;
else
b = b % a;
}
return a + b;
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
boolean isOuterFile = false;
public void run() {
try {
if (isOuterFile) {
reader = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
out = new PrintWriter(System.out);
} else {
reader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tokenizer = null;
// long t=new Date().getTime();
solve();
// writer.println(t-new Date().getTime());
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
1c0a55fada76c9b5a818e0c577a09dac
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class TaskB {
BufferedReader br;
PrintWriter out;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
class Rec implements Comparable<Rec> {
int c, id, t;
Rec(int c, int t, int id) {
this.c = c;
this.t = t;
this.id = id;
}
public int compareTo(Rec r) {
return r.c - this.c;
}
}
double otcheNash(ArrayList<Rec> a) {
boolean fl = false;
double min = 1e10;
double sum = 0;
Rec t;
for (int i = 0; i < a.size(); i++) {
t = a.get(i);
if (t.t == 1) {
fl = true;
}
sum += t.c;
min = Math.min(min, t.c);
}
if (fl) {
sum -= min / 2.0;
}
return sum;
}
void solve() throws IOException {
int n = nextInt(), k = nextInt();
ArrayList<Rec> ra1 = new ArrayList<Rec>(), ra2 = new ArrayList<Rec>();
int c, t;
for (int i = 0; i < n; i++) {
c = nextInt();
t = nextInt();
if (t == 1) {
ra1.add(new Rec(c, t, i));
} else {
ra2.add(new Rec(c, t, i));
}
}
int l1 = ra1.size(), l2 = ra2.size();
Collections.sort(ra1);
Collections.sort(ra2);
ArrayList<Rec>[] ans = new ArrayList[k];
for (int i = 0; i < k; i++) {
ans[i] = new ArrayList<Rec>();
}
int i1 = 0, ia = 0;
while (i1 < l1 && ia < k) {
ans[ia].add(ra1.get(i1));
ia++;
i1++;
}
while (i1 < l1) {
ans[k - 1].add(ra1.get(i1));
i1++;
}
int i2 = 0;
while (ia < k && i2 < l2) {
ans[ia].add(ra2.get(i2));
ia++;
i2++;
}
while (i2 < l2) {
ans[k - 1].add(ra2.get(i2));
i2++;
}
double sum = 0;
for (int i = 0; i < k; i++) {
sum += otcheNash(ans[i]);
}
out.printf("%.1f\n", sum);
for (int i = 0; i < k; i++) {
out.print(ans[i].size() + " ");
for (Rec g : ans[i]) {
out.print((g.id + 1) + " ");
}
out.println();
}
}
void run() throws IOException {
// br = new BufferedReader(new FileReader("taskb.in"));
// out = new PrintWriter("taskb.out");
// br = new BufferedReader(new FileReader("input.txt"));
// out = new PrintWriter("output.txt");
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
br.close();
out.close();
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new TaskB().run();
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
11ac0741b96c436b491bee0611d405ce
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: [email protected]
* Date: 11.03.12
*/
public class B {
public static void main(String[] args) throws IOException {
Scanner r = new Scanner(System.in);
// BufferedReader r = new BufferedReader(new FileReader(new File("main/a.in")));
// System.setOut(new PrintStream(new File("main/a.out")));
PrintWriter w = new PrintWriter(System.out);
int n = r.nextInt();
int k = r.nextInt();
U[] a = new U[n];
List<Integer>[] ans = new List[k];
int chairs = 0;
double sum = 0;
for (int i = 0; i < n; i++) {
int c = r.nextInt();
int t = r.nextInt();
a[i] = new U(i+1, c, t);
sum += c;
if (t == 1) chairs++;
}
Arrays.sort(a);
ans[0] = new LinkedList<Integer>();
int t = 1;
for (U u : a) {
// w.print(" " + u.s);
if (t == k) {
ans[0].add(u.n);
} else if (u.t == 1) {
ans[t] = new ArrayList<Integer>(1);
ans[t].add(u.n);
sum -= (u.s/2.0);
t++;
} else {
ans[0].add(u.n);
}
}
// w.println();
while (t < k) {
ans[t] = new ArrayList<Integer>(1);
ans[t].add(ans[0].remove(0));
t++;
}
if (chairs >= k) {
sum -= a[n-1].s/2.0;
}
w.println(String.format("%.1f", sum));
for (List<Integer> e: ans) {
w.print(e.size());
for (Integer integer : e) {
w.print(" " + integer);
}
w.println();
}
w.close();
}
static public class U implements Comparable<U> {
public final int n;
public final int s;
public final int t;
public U(int n, int s, int t) {
this.n = n;
this.s = s;
this.t = t;
}
public int compareTo(U o) {
return o.s - s;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
aeeb9c9bb618cbfaef527ea5f108e58b
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
/**
* Discounts
*
* One day Polycarpus stopped by a supermarket on his way home. It turns out
* that the supermarket is having a special offer for stools. The offer is as
* follows: if a customer's shopping cart contains at least one stool, the
* customer gets a 50% discount on the cheapest item in the cart (that is, it
* becomes two times cheaper). If there are several items with the same minimum
* price, the discount is available for only one of them!
*
* Polycarpus has k carts, and he wants to buy up all stools and pencils from
* the supermarket. Help him distribute the stools and the pencils among the
* shopping carts, so that the items' total price (including the discounts) is
* the least possible.
*
* Polycarpus must use all k carts to purchase the items, no shopping cart can
* remain empty. Each shopping cart can contain an arbitrary number of stools
* and/or pencils.
*
* Input
* The first input line contains two integers n and k (1 <= k <= n <= 103) β the
* number of items in the supermarket and the number of carts, correspondingly.
* Next n lines describe the items as "ci ti" (without the quotes), where ci
* (1 <= ci <= 10^9) is an integer denoting the price of the i-th item, ti
* (1 <= ti <= 2) is an integer representing the type of item i (1 for a stool
* and 2 for a pencil). The numbers in the lines are separated by single spaces.
*
* Output
* In the first line print a single real number with exactly one decimal place
* β the minimum total price of the items, including the discounts.
*
* In the following k lines print the descriptions of the items in the carts. In
* the i-th line print the description of the i-th cart as "t b1 b2 ... bt"
* (without the quotes), where t is the number of items in the i-th cart, and
* the sequence b1, b2, ..., bt (1 <= bj <= n) gives the indices of items to put
* in this cart in the optimal distribution. All indices of items in all carts
* should be pairwise different, each item must belong to exactly one cart. You
* can print the items in carts and the carts themselves in any order. The items
* are numbered from 1 to n in the order in which they are specified in the
* input.
*
* If there are multiple optimal distributions, you are allowed to print any of
* them.
*
* Sample test(s)
* Input
* 3 2
* 2 1
* 3 2
* 3 1
* Output
* 5.5
* 2 1 2
* 1 3
*
* Input
* 4 3
* 4 1
* 1 2
* 2 2
* 3 2
* Output
* 8.0
* 1 1
* 2 4 2
* 1 3
*
* Note
* In the first sample case the first cart should contain the 1st and 2nd items,
* and the second cart should contain the 3rd item. This way each cart has a
* stool and each cart has a 50% discount for the cheapest item. The total price
* of all items will be: 2Β·0.5 + (3 + 3Β·0.5) = 1 + 4.5 = 5.5.
*
* @author Europa
*/
public class Discounts {
private static final int STOOL = 1;
private static final int INDEX = 0;
private static final int PRICE = 1;
private static final int TYPE = 2;
private static final int CART = 3;
private static final int INVALID = -1;
private static final double DISCOUNT = 0.5;
private static void distribute(int K, int[][] items) {
Arrays.sort(items, new Comparator<int[]>() {
@Override
public int compare(int[] item1, int[] item2) {
if (item1[TYPE] == item2[TYPE]) return item2[PRICE] - item1[PRICE];
return item1[TYPE] - item2[TYPE];
}
});
int i = 0, cart = 0;
for (; i < K && items[i][TYPE] == STOOL; i++, cart++) {
items[i][CART] = i + 1;
}
for (; i < items.length && items[i][TYPE] == STOOL; i++) {
items[i][CART] = K;
}
for (; i < items.length && cart < K; i++) {
items[i][CART] = ++cart;
}
for (; i < items.length && items[K - 1][PRICE] < items[i][PRICE]; i++) {
items[i][CART] = K;
}
for (; i < items.length; i++) { items[i][CART] = K; }
Arrays.sort(items, new Comparator<int[]>() {
@Override
public int compare(int[] item1, int[] item2) {
if (item1[TYPE] == item2[TYPE]) return item1[PRICE] - item2[PRICE];
return item1[TYPE] - item2[TYPE];
}
});
int[][] distribution = new int[K][items.length + 1];
for (int j = 0; j < items.length; j++) {
cart = items[j][CART] - 1;
distribution[cart][0]++;
distribution[cart][distribution[cart][0]] = items[j][INDEX];
}
Arrays.sort(items, new Comparator<int[]>() {
@Override
public int compare(int[] item1, int[] item2) {
return item1[INDEX] - item2[INDEX];
}
});
double total = 0;
for (int k = 0; k < K; k++) {
if (distribution[k][0] == 0) continue;
boolean discount = items[distribution[k][1] - 1][TYPE] == STOOL;
int minimum = INVALID;
for (int j = 1; j <= items.length && j <= distribution[k][0]; j++) {
int cost = items[distribution[k][j] - 1][PRICE];
total += cost; if (minimum == INVALID || minimum > cost) minimum = cost;
}
if (discount) total -= minimum * (1 - DISCOUNT);
}
System.out.printf("%.1f\n", total);
for (int k = 0; k < K; k++) {
System.out.print(distribution[k][0]);
System.out.print(" ");
for (int j = 1; j <= items.length && j <= distribution[k][0]; j++) {
System.out.print(distribution[k][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int K = scanner.nextInt();
int[][] items = new int[N][4];
for (int i = 0; i < N; i++) {
items[i][INDEX] = i + 1;
items[i][PRICE] = scanner.nextInt();
items[i][TYPE] = scanner.nextInt();
items[i][CART] = -1;
}
Discounts.distribute(K, items);
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
24cc6c37f9e5f1d5768557bd8ea80218
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
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.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class B {
public static void main(String[] args) throws IOException {
final int n = IOFast.nextInt();
final int k = IOFast.nextInt();
long res = 0;
int[][] xs = new int[n][3];
for(int i = 0; i < n; i++) {
final int c = IOFast.nextInt();
final int t = IOFast.nextInt();
res += 2L * c;
xs[i][0] = c;
xs[i][1] = t;
xs[i][2] = i + 1;
}
Arrays.sort(xs, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] != o2[1] ? o1[1] - o2[1] : o2[0] - o1[0];
}
});
for(int i = 0; i < k - 1 && xs[i][1] == 1; i++) {
res -= xs[i][0];
}
if(xs[k - 1][1] == 1) {
int min = Integer.MAX_VALUE;
for(int i = k - 1; i < n; i++) {
min = Math.min(min, xs[i][0]);
}
res -= min;
}
IOFast.out.printf("%.1f\n", res / 2.0);
for(int i = 0; i < k - 1; i++) {
IOFast.out.println("1 " + xs[i][2]);
}
IOFast.out.print(xs.length - k + 1);
for(int i = k - 1; i < xs.length; i++) {
IOFast.out.print(" " + xs[i][2]);
}
IOFast.out.println();
IOFast.out.flush();
}
static public class IOFast {
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static PrintWriter out = new PrintWriter(System.out);
// private static final int BUFFER_SIZE = 50 * 200000;
private static final StringBuilder buf = new StringBuilder();
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
static {
for(int i = 0; i < 10; i++) {
isDigit['0' + i] = true;
}
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
}
static boolean endInput;
private static int nextInt() throws IOException {
boolean plus = false;
int ret = 0;
while(true) {
final int c = in.read();
if(c == -1) {
endInput = true;
return Integer.MIN_VALUE;
}
if(isDigit[c]) {
if(c != '-') {
plus = true;
ret = c - '0';
}
break;
}
}
while(true) {
final int c = in.read();
if(c == -1 || !isDigit[c]) {
break;
}
ret = ret * 10 + c - '0';
}
return plus ? ret : -ret;
}
private static long nextLong() throws IOException {
boolean plus = false;
long ret = 0;
while(true) {
final int c = in.read();
if(c == -1) {
endInput = true;
return Integer.MIN_VALUE;
}
if(isDigit[c]) {
if(c != '-') {
plus = true;
ret = c - '0';
}
break;
}
}
while(true) {
final int c = in.read();
if(c == -1 || !isDigit[c]) {
break;
}
ret = ret * 10 + c - '0';
}
return plus ? ret : -ret;
}
private static String next() throws IOException {
buf.setLength(0);
while(true) {
final int c = in.read();
if(c == -1) {
endInput = true;
return "-1";
}
if(!isSpace[c]) {
buf.append((char)c);
break;
}
}
while(true) {
final int c = in.read();
if(c == -1 || isSpace[c]) {
break;
}
buf.append((char)c);
}
return buf.toString();
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
9297951d71cbc2fa9dca089191db2d8d
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class b extends Thread {
BufferedReader bf;
PrintWriter out;
FastScanner in;
void solve() throws Exception {
int n = in.nextInt();
int k = in.nextInt();
point a[] = new point[n];
for (int i = 0; i<n; i++)
a[i] = new point(in.nextInt(), in.nextInt(), i + 1);
Arrays.sort(a);
ArrayList<Integer>[] corsins = new ArrayList[k];
for (int i = 0; i<k; i++)
corsins[i] = new ArrayList<Integer>();
double ans = 0;
for (int i = 0; i<k-1; i++){
corsins[i].add(a[i].spec);
if (a[i].id == 1)
ans += (double)a[i].x/2;
else ans += a[i].x;
}
if (a[k-1].id == 1){
double min = a[k-1].x;
for (int i = k; i<n; i++)
min = Math.min(a[i].x, min);
ans -= min/2;
}
for (int i = k - 1; i<n; i++){
corsins[k-1].add(a[i].spec);
ans += a[i].x;
}
out.printf("%.1f\n", ans);
for (int i = 0; i<k; i++){
out.print(corsins[i].size() + " ");
for (int x : corsins[i])
out.print(x + " ");
out.println();
}
}
public void run() {
try {
bf = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
in = new FastScanner(bf);
solve();
out.flush();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
}
public static void main(String args[]) {
new b().start();
}
class point implements Comparable<point> {
int x, id, spec;
public point(int x, int id, int spec) {
this.x = x;
this.id = id;
this.spec = spec;
}
public int compareTo(point o) {
if (this.id == 1 && o.id == 1)
return o.x - this.x;
if (this.id == 1 && o.id == 2)
return -1;
if (this.id == 2 && o.id == 1)
return 1;
return o.x - this.x;
}
}
private class FastScanner {
BufferedReader bf;
StringTokenizer st;
public FastScanner(BufferedReader bf) {
this.bf = bf;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(bf.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public Double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
public BigInteger nextBigInteger() throws Exception {
return new BigInteger(nextToken());
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
5a26fc926ab21865e71a001d4449227a
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Thread(null, new Runnable() {
public void run() {
try {
new Main().run();
} catch (Throwable e) {
e.printStackTrace();
exit(999);
}
}
}, "1", 1 << 23).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
private void solve() throws IOException {
int n = nextInt();
int k = nextInt();
Item[] item = new Item[n];
for (int i = 0; i < n; i++)
item[i] = new Item(nextInt(), nextInt(), i + 1);
sort(item);
long cost = 0;
ArrayList<Integer>[] ans = new ArrayList[k];
for (int i = 0; i < k; i++)
ans[i] = new ArrayList<Integer>();
int pos = n - 1;
for (int i = 0; i < k - 1; i++) {
for (;pos >= k - i - 1; pos--) {
ans[i].add(item[pos].no);
if (item[pos].type == 1) {
cost += item[pos].cost;
pos--;
break;
} else {
cost += 2 * item[pos].cost;
}
}
}
boolean t = false;
for (int i = 0; i <= pos; i++) {
t |= item[i].type == 1;
cost += 2 * item[i].cost;
ans[k - 1].add(item[i].no);
}
if (t)
cost -= item[0].cost;
out.println((cost >> 1) + "." + (5 * (cost & 1)));
for (int i = 0; i < k; i++) {
out.print(ans[i].size());
for (Integer a : ans[i])
out.print(" " + a);
out.println();
}
}
class Item implements Comparable<Item> {
long cost;
int type;
int no;
Item(long cost, int type, int no) {
this.cost = cost;
this.type = type;
this.no = no;
}
@Override
public int compareTo(Item it) {
if (cost != it.cost)
return cost < it.cost ? -1 : 1;
return type - it.type;
}
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
5025a7d7ad47f169ba069e85f86285a0
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Discount {
public static void main(String[] args) {
new Discount().run();
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
boolean eof = false;
Random rand = new Random(12345);
private void run() {
Locale.setDefault(Locale.US);
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(566);
}
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
private void solve() throws IOException {
int n = nextInt();
int k = nextInt();
ArrayList<Item> chair = new ArrayList<Discount.Item>();
ArrayList<Item> pencil = new ArrayList<Discount.Item>();
for (int i = 0; i < n; i++) {
long c = nextLong();
int t = nextInt();
Item it = new Item(c, t, i);
if (it.type == 1) {
chair.add(it);
} else {
pencil.add(it);
}
}
ArrayList<Item>[] bucket = new ArrayList[k];
for (int i = 0; i < bucket.length; i++) {
bucket[i] = new ArrayList<Discount.Item>();
}
Collections.sort(chair);
Collections.sort(pencil);
for (int i = 0; i < bucket.length; i++) {
if (!chair.isEmpty()) {
bucket[i].add(chair.remove(chair.size() - 1));
}
}
for (int i = 0; i < bucket.length; i++) {
if (bucket[i].isEmpty()) {
bucket[i].add(pencil.remove(pencil.size() - 1));
}
}
for (int i = 0; i < bucket.length; i++) {
long min = bucket[i].get(0).c;
while (!chair.isEmpty() && chair.get(chair.size() - 1).c >= min) {
bucket[i].add(chair.remove(chair.size() - 1));
}
while (!pencil.isEmpty() && pencil.get(pencil.size() - 1).c >= min) {
bucket[i].add(pencil.remove(pencil.size() - 1));
}
}
bucket[bucket.length - 1].addAll(pencil);
bucket[bucket.length - 1].addAll(chair);
long ans = 0;
for (int i = 0; i < bucket.length; i++) {
Collections.sort(bucket[i]);
boolean good = false;
for (Item it : bucket[i]) {
ans += 2 * it.c;
good |= it.type == 1;
}
if (good) {
ans -= bucket[i].get(0).c;
}
}
out.print(ans / 2 + ".");
if (ans % 2 == 0) {
out.println("0");
} else {
out.println("5");
}
for (int i = 0; i < bucket.length; i++) {
out.print(bucket[i].size());
for (Item it : bucket[i]) {
out.print(" " + (it.n + 1));
}
out.println();
}
}
class Item implements Comparable<Item> {
public Item(long c2, int t, int i) {
c = c2;
type = t;
n = i;
}
int type;
long c;
int n;
@Override
public int compareTo(Item o) {
return c < o.c ? -1 : 1;
}
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
5f09872e0b399115105b011134e36936
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
/**
* Jerry Ma
* Program discounts
*/
import java.io.*;
import java.util.*;
public class discounts {
static BufferedReader cin;
static StringTokenizer tk;
public static void main (String [] args) throws IOException {
init();
Item [] stools = new Item[1000], pencils = new Item[1000];
Item [] [] carts = new Item[1000][1000];
int [] itemsPerCart = new int[1000];
int numStools = 0, numPencils = 0, numItems = gInt(), numCarts = gInt();
for (int count = 0; count < numItems; count ++) {
int price = gInt(), type = gInt();
if (type == 1) {
stools[numStools] = new Item(true, count, price);
numStools ++;
}
else {
pencils[numPencils] = new Item(false, count, price);
numPencils ++;
}
}
Arrays.sort(stools, 0, numStools);
Item.ascending = true;
Arrays.sort(pencils, 0, numPencils);
double price = 0;
long lowestPrice = 999999999999L;
for (int count = 0; count < numStools; count ++) {
long p = stools[count].price;
int cart = count;
if (cart >= numCarts - 1) {
cart = numCarts - 1;
price += p;
if (p < lowestPrice)
lowestPrice = p;
}
else
price += p / 2.0;
carts[cart][itemsPerCart[cart]] = stools[count];
itemsPerCart[cart] ++;
}
for (int count = 0; count < numPencils; count ++) {
long p = pencils[count].price;
int cart = count + numStools;
if (cart >= numCarts - 1) {
cart = numCarts - 1;
if (p < lowestPrice)
lowestPrice = p;
}
price += p;
carts[cart][itemsPerCart[cart]] = pencils[count];
itemsPerCart[cart] ++;
}
if (numStools >= numCarts)
price -= lowestPrice / 2.0;
System.out.printf("%.1f\n", price);
for (int count = 0; count < numCarts; count ++) {
System.out.print(itemsPerCart[count]);
for (int count2 = 0; count2 < itemsPerCart[count]; count2 ++)
System.out.printf(" %d", carts[count][count2].index + 1);
System.out.println();
}
quit();
}
public static void init () {
cin = new BufferedReader(new InputStreamReader(System.in));
tk = new StringTokenizer("");
}
public static void quit () throws IOException {
System.out.flush();
System.exit(0);
}
public static String token () throws IOException {
while (!tk.hasMoreTokens())
tk = new StringTokenizer(cin.readLine());
return tk.nextToken();
}
public static int gInt () throws IOException {
return Integer.parseInt(token());
}
public static long gLong () throws IOException {
return Long.parseLong(token());
}
public static double gDouble () throws IOException {
return Double.parseDouble(token());
}
}
class Item implements Comparable <Item> {
static boolean ascending = false;
final boolean stool;
final int index;
final long price;
public Item (boolean s, int i, int p) {
stool = s;
index = i;
price = p;
}
public int compareTo (Item o) {
if (price < o.price) {
if (ascending)
return -1;
return 1;
}
if (ascending)
return 1;
return -1;
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
ca94517eba7c67bf6341d8f38b299f39
|
train_001.jsonl
|
1331478300
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class B
{
static int min(int a, int b)
{
return (a > b ? b : a);
}
static int max(int a, int b)
{
return (a > b ? a : b);
}
/**
* @param args
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
ArrayList<Pair> tab = new ArrayList<Pair>();
ArrayList<Pair> kar = new ArrayList<Pair>();
for (int i = 0; i < n; i++)
{
int c = in.nextInt();
int t = in.nextInt();
if (t == 1)
{
tab.add(new Pair(i + 1, c));
}
else
kar.add(new Pair(i + 1, c));
}
Collections.sort(tab);
ArrayList<ArrayList<Pair>> list = new ArrayList<ArrayList<Pair>>(k);
for (int i = 0; i < k; i++)
{
list.add(new ArrayList<Pair>());
}
double result = 0;
if (k > tab.size())
{
for (int i = 0; i < tab.size(); i++)
{
list.get(i).add(tab.get(i));
result += tab.get(i).c / 2.;
}
for (int i = tab.size(); i < k; i++)
{
list.get(i).add(kar.get(i - tab.size()));
result += kar.get(i - tab.size()).c;
}
for (int i = k - tab.size(); i < kar.size(); i++)
{
list.get(k - 1).add(kar.get(i));
result += kar.get(i).c;
}
}
else
{
for (int i = 0; i < k; i++)
{
list.get(i).add(tab.get(tab.size() - 1 - i));
}
for (int i = 0; i < tab.size() - k; i++)
{
list.get(k - 1).add(tab.get(i));
}
for (int i = 0; i < kar.size(); i++)
{
list.get(k - 1).add(kar.get(i));
}
for (ArrayList<Pair> l : list)
{
Collections.sort(l);
}
for (ArrayList<Pair> l : list)
{
result += l.get(0).c / 2.;
for (int i = 1; i < l.size(); i++)
{
result += l.get(i).c;
}
}
}
long x = (long) (result + 0.000000000001);
double w = result - x;
if (w - 0.00001 < 0)
System.out.println("" + x + ".0");
else
System.out.println("" + x + ".5");
for (ArrayList<Pair> l : list)
{
System.out.print(l.size());
for (Pair p : l)
{
System.out.print(" " + p.nom);
}
System.out.println();
}
}
}
class Pair implements Comparable<Pair>
{
int nom;
double c;
public Pair(int nom, int c)
{
this.nom = nom;
this.c = c;
}
@Override
public int compareTo(Pair o)
{
return (c > o.c + 0.00000001) ? 1 : ((c < o.c - 0.00000001) ? -1 : 0);
}
}
|
Java
|
["3 2\n2 1\n3 2\n3 1", "4 3\n4 1\n1 2\n2 2\n3 2"]
|
3 seconds
|
["5.5\n2 1 2\n1 3", "8.0\n1 1\n2 4 2\n1 3"]
|
NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5β+β(3β+β3Β·0.5)β=β1β+β4.5β=β5.5.
|
Java 6
|
standard input
|
[
"constructive algorithms",
"sortings",
"greedy"
] |
06c7834aa4d06d6fcebfa410054f1b8c
|
The first input line contains two integers n and k (1ββ€βkββ€βnββ€β103) β the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1ββ€βciββ€β109) is an integer denoting the price of the i-th item, ti (1ββ€βtiββ€β2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
| 1,700 |
In the first line print a single real number with exactly one decimal place β the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1,βb2,β...,βbt (1ββ€βbjββ€βn) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
|
standard output
| |
PASSED
|
8c69fbce2a71e0ab20afa0d4fa838742
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class F {
FastScanner in;
PrintWriter out;
void solve() {
int n = in.nextInt();
int m = in.nextInt();
List<Edge>[] g = new List[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int fr = in.nextInt() - 1;
int to = in.nextInt() - 1;
g[fr].add(new Edge(to, (i + 1) + ""));
g[to].add(new Edge(fr, (i + 1) + ""));
}
int root = getNode(0, 0, 0);
int[] dp = new int[n];
Arrays.fill(dp, -1);
dp[0] = root;
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(0, root));
boolean[] was = new boolean[n];
while (!pq.isEmpty()) {
Node node = pq.poll();
if (was[node.vertex]) {
continue;
}
for (Edge e : g[node.vertex]) {
if (!was[e.to]) {
int len = getNext(node.len, e.s);
if (dp[e.to] == -1 || cmp(len, dp[e.to]) < 0) {
dp[e.to] = len;
pq.add(new Node(e.to, len));
}
}
}
}
for (int i = 1; i < n; i++) {
out.println(hash[dp[i]]);
}
}
int getNext(int from, String s) {
for (int i = 0; i < s.length(); i++) {
int t = s.charAt(i) - '0';
if (next[t][from] == -1) {
next[t][from] = getNode(curH[from] + 1, from, t);
}
from = next[t][from];
}
return from;
}
class Node implements Comparable<Node> {
int vertex, len;
public Node(int vertex, int len) {
this.vertex = vertex;
this.len = len;
}
@Override
public int compareTo(Node node) {
return cmp(len, node.len);
}
}
int cmp(int n1, int n2) {
if (curH[n1] != curH[n2]) {
return Integer.compare(curH[n1], curH[n2]);
}
return lca(n1, n2);
}
int lca(int x, int y) {
for (int i = up.length - 1; i >= 0; i--) {
if (up[i][x] != up[i][y]) {
x = up[i][x];
y = up[i][y];
}
}
return Integer.compare(prev[x], prev[y]);
}
final int MAX = (int) 2e5 * 7;
int[][] next = new int[10][MAX];
int[] curH = new int[MAX];
int[] hash = new int[MAX];
final int mod = (int) 1e9 + 7;
int[][] up = new int[18][MAX];
int[] prev = new int[MAX];
int nodes = 0;
int getNode(int myHieght, int parent, int digit) {
int ret = nodes++;
curH[ret] = myHieght;
hash[ret] = (int) ((hash[parent] * 10L + digit) % mod);
prev[ret] = digit;
for (int i = 0; i < 10; i++) {
next[i][ret] = -1;
}
up[0][ret] = parent;
for (int i = 1; i < up.length; i++) {
up[i][ret] = up[i - 1][up[i - 1][ret]];
}
return ret;
}
class Edge {
int to;
String s;
public Edge(int to, String s) {
this.to = to;
this.s = s;
}
}
void run() {
try {
in = new FastScanner(new File("F.in"));
out = new PrintWriter(new File("F.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new F().runIO();
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
988def9e6ee50f60c95f73e44d85a46e
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class KoalaNotebook {
static final int maxsz = 1000000;
static final long mod = 1000000007L;
static ArrayList<Edge>[] graph;
static int top;
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out, false);
int n = scanner.nextInt(), m = scanner.nextInt();
graph = new ArrayList[maxsz];
top = n;
for(int i = 0; i < maxsz; i++) graph[i] = new ArrayList<>();
for(int i = 0; i < m; i++) {
int u = scanner.nextInt()-1, v = scanner.nextInt()-1;
addEdge(u, v, i + 1);
addEdge(v, u, i + 1);
}
long[] vals = new long[maxsz];
Arrays.fill(vals, -1);
vals[0] = 0;
int layer = 0;
ArrayDeque<Pair> queue = new ArrayDeque<>();
long tt = 0;
queue.offer(new Pair(0, tt++));
while(!queue.isEmpty()) {
ArrayList<Integer> nw = new ArrayList<>();
while(!queue.isEmpty() && queue.peek().b == layer) { nw.add(queue.poll().a); }
if (nw.size() == 0) continue;
for(int i = 0; i < 10; i++) {
int ff = 0;
for(int ind: nw) {
for(Edge edge: graph[ind]) {
if (edge.val ==i && vals[edge.to] < 0) {
vals[edge.to] = (10L*vals[ind] + edge.val) % mod;
queue.offer(new Pair(edge.to, tt));
ff = 1;
}
}
}
tt += ff;
}
layer++;
}
for(int i = 1; i < n; i++) {
out.println(vals[i]);
}
out.flush();
}
static class Pair {
int a;long b;
public Pair(int aa, long bb) {
a = aa; b= bb;
}
}
static void addEdge(int x, int y, int v) {
ArrayList<Integer> dig = new ArrayList<>();
while(v > 0) {
dig.add(v%10); v/=10;
}
Collections.reverse(dig);
int cur = x;
for(int i = 0; i < dig.size()-1; i++) {
graph[cur].add(new Edge(top++, dig.get(i)));
cur = top-1;
}
graph[cur].add(new Edge(y, dig.get(dig.size()-1)));
}
static class Edge {
int to, val;
public Edge(int tt, int vv) {
to = tt; val = vv;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
06c7c0f04d0df5ac12fa3a17565f098b
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
static final int MODULO = (int) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n0 = in.nextInt();
int m0 = in.nextInt();
int[] first = new int[10 * (n0 + 12 * m0)];
int[] next = new int[2 * (7 * m0)];
int[] dest = new int[2 * (7 * m0)];
int n = n0;
int m = 0;
Arrays.fill(first, -1);
for (int i = 1; i <= m0; ++i) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
for (int iter = 0; iter < 2; ++iter) {
int tmp = i;
int cur = iter == 0 ? x : y;
while (tmp > 0) {
int d = tmp % 10;
tmp /= 10;
int nxt = (tmp == 0 ? (iter == 0 ? y : x) : n++);
dest[m] = cur;
next[m] = first[10 * nxt + d];
first[10 * nxt + d] = m;
++m;
cur = nxt;
}
}
}
int[] dist = new int[n];
Arrays.fill(dist, -1);
dist[0] = 0;
int[] queue = new int[n + 1];
boolean[] blockStart = new boolean[n + 1];
int qt = 0;
int qh = 1;
blockStart[0] = true;
queue[0] = 0;
blockStart[1] = true;
while (qt < qh) {
int qm = qt + 1;
while (qm < qh && !blockStart[qm]) ++qm;
for (int d = 0; d < 10; ++d) {
for (int i = qt; i < qm; ++i) {
int cur = queue[i];
int e = first[cur * 10 + d];
while (e >= 0) {
int b = dest[e];
if (dist[b] < 0) {
dist[b] = (int) ((dist[cur] * (long) 10 + d) % MODULO);
queue[qh++] = b;
}
e = next[e];
}
}
blockStart[qh] = true;
}
qt = qm;
}
for (int i = 1; i < n0; ++i) {
if (dist[i] < 0) throw new RuntimeException();
out.println(dist[i]);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
df6535c5f84fbe49309d9d838d34c566
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class F {
static final long mod = 1000000007;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int N = n+8*m;
ArrayList<Pair>[] g = new ArrayList[N];
for(int i = 0; i < N; i++) {
g[i] = new ArrayList<Pair>();
}
int currv = n;
for(int i = 1; i <= m; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken())-1;
int v = Integer.parseInt(st.nextToken())-1;
if(i < 10) {
g[u].add(new Pair(v, i));
g[v].add(new Pair(u, i));
}
else {
int aux = i;
g[currv].add(new Pair(v, aux % 10)); aux /= 10;
while(aux >= 10) {
g[currv+1].add(new Pair(currv, aux % 10));
currv++; aux /= 10;
}
g[u].add(new Pair(currv, aux)); currv++;
aux = i;
g[currv].add(new Pair(u, aux % 10)); aux /= 10;
while(aux >= 10) {
g[currv+1].add(new Pair(currv, aux % 10));
currv++; aux /= 10;
}
g[v].add(new Pair(currv, aux)); currv++;
}
}
long[] dist = new long[N];
Arrays.fill(dist, -1);
LinkedList<Pair> q = new LinkedList<>();
q.add(new Pair(0, 0));
dist[0] = 0;
int ts = 0;
while(!q.isEmpty()) {
Pair p = q.pollFirst(); ts++;
PriorityQueue<Pair> edgestocheck = new PriorityQueue<Pair>();
edgestocheck.addAll(g[p.u]);
int currts = p.d;
while(!q.isEmpty() && q.peek().d == currts) {
edgestocheck.addAll(g[q.poll().u]);
}
while(!edgestocheck.isEmpty()) {
Pair r = edgestocheck.poll();
if(dist[r.u] < 0) {
dist[r.u] = (dist[p.u] * 10L + r.d) % mod;
q.add(new Pair(r.u, ts * 10 + r.d));
}
}
}
for(int i = 1; i < n; i++) {
bw.write(dist[i]+"\n");
}
bw.flush();
}
static class Pair implements Comparable<Pair>{
int u, d;
public Pair(int v, int d) {
this.u = v; this.d = d;
}
@Override
public int compareTo(Pair p) {
return d - p.d;
}
public String toString() {
return u+" ("+d+")";
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
1dbdb5bc9e30e11f438a78a9def0be87
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class F {
static final long mod = 1000000007;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int N = n+8*m;
ArrayList<Pair>[] g = new ArrayList[N];
for(int i = 0; i < N; i++) {
g[i] = new ArrayList<Pair>();
}
int currv = n;
for(int i = 1; i <= m; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken())-1;
int v = Integer.parseInt(st.nextToken())-1;
if(i < 10) {
g[u].add(new Pair(v, i));
g[v].add(new Pair(u, i));
}
else {
int aux = i;
g[currv].add(new Pair(v, aux % 10)); aux /= 10;
while(aux >= 10) {
g[currv+1].add(new Pair(currv, aux % 10));
currv++; aux /= 10;
}
g[u].add(new Pair(currv, aux)); currv++;
aux = i;
g[currv].add(new Pair(u, aux % 10)); aux /= 10;
while(aux >= 10) {
g[currv+1].add(new Pair(currv, aux % 10));
currv++; aux /= 10;
}
g[v].add(new Pair(currv, aux)); currv++;
}
}
int[] dist = new int[N];
Arrays.fill(dist, -1);
LinkedList<Pair> q = new LinkedList<>();
q.add(new Pair(0, 0));
dist[0] = 0;
int ts = 0;
while(!q.isEmpty()) {
Pair p = q.pollFirst(); ts++;
PriorityQueue<Pair> edgestocheck = new PriorityQueue<Pair>();
edgestocheck.addAll(g[p.u]);
int currts = p.d;
while(!q.isEmpty() && q.peek().d == currts) {
edgestocheck.addAll(g[q.poll().u]);
}
while(!edgestocheck.isEmpty()) {
Pair r = edgestocheck.poll();
if(dist[r.u] < 0) {
dist[r.u] = (int)(((long)dist[p.u] * 10L + (long)r.d) % mod);
q.add(new Pair(r.u, ts * 10 + r.d));
}
}
}
for(int i = 1; i < n; i++) {
// if(dist[i] < 0) dist[i] += mod;
bw.write(dist[i]+"\n");
}
bw.flush();
}
static class Pair implements Comparable<Pair>{
int u, d;
public Pair(int v, int d) {
this.u = v; this.d = d;
}
@Override
public int compareTo(Pair p) {
return d - p.d;
}
public String toString() {
return u+" ("+d+")";
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
93cd0b6a0a6671f3e4e4f44f08ea4bc8
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.max;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import static java.util.Arrays.copyOf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class F {
static class IntList {
int data[] = new int[3];
int size = 0;
boolean isEmpty() {
return size == 0;
}
int size() {
return size;
}
int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return data[index];
}
void clear() {
size = 0;
}
void set(int index, int value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
data[index] = value;
}
void expand() {
if (size >= data.length) {
data = copyOf(data, (data.length << 1) + 1);
}
}
void insert(int index, int value) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
expand();
arraycopy(data, index, data, index + 1, size++ - index);
data[index] = value;
}
int delete(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int value = data[index];
arraycopy(data, index + 1, data, index, --size - index);
return value;
}
void push(int value) {
expand();
data[size++] = value;
}
int pop() {
if (size == 0) {
throw new NoSuchElementException();
}
return data[--size];
}
void unshift(int value) {
expand();
arraycopy(data, 0, data, 1, size++);
data[0] = value;
}
int shift() {
if (size == 0) {
throw new NoSuchElementException();
}
int value = data[0];
arraycopy(data, 1, data, 0, --size);
return value;
}
}
static class LongLongMap {
static final long EMPTY = Long.MIN_VALUE;
long data[] = new long[4];
{
data[0] = EMPTY;
data[2] = EMPTY;
}
int size = 0;
boolean isEmpty() {
return size == 0;
}
int size() {
return size;
}
void clear() {
for (int i = 0; i < data.length; i += 2) {
data[i] = EMPTY;
}
size = 0;
}
static int hash(long key) {
long hash = key * 1000000007;
hash ^= hash >> 16;
hash ^= hash >> 24;
return (int) hash;
}
boolean have(long key) {
if (key == EMPTY) {
throw new IllegalArgumentException();
}
for (int mask = data.length - 2, i = hash(key) & mask;; i = (i - 1) & mask) {
long cur = data[i];
if (cur == key) {
return true;
} else if (cur == EMPTY) {
return false;
}
}
}
long get(long key, long default_) {
if (key == EMPTY) {
throw new IllegalArgumentException();
}
for (int mask = data.length - 2, i = hash(key) & mask;; i = (i - 1) & mask) {
long cur = data[i];
if (cur == key) {
return data[i + 1];
} else if (cur == EMPTY) {
return default_;
}
}
}
static long[] resize(long data[], int newCapacity) {
int oldCapacity = data.length;
long ndata[] = new long[newCapacity];
for (int i = 0; i < newCapacity; i += 2) {
ndata[i] = EMPTY;
}
for (int mask = newCapacity - 2, i = 0; i < oldCapacity; i += 2) {
long cur = data[i];
if (cur == EMPTY) {
continue;
}
for (int j = hash(cur) & mask;; j = (j - 1) & mask) {
if (ndata[j] == EMPTY) {
ndata[j] = cur;
ndata[j + 1] = data[i + 1];
break;
}
}
}
return ndata;
}
void set(long key, long value) {
if (key == EMPTY) {
throw new IllegalArgumentException();
}
long data[] = this.data;
for (int capacity = data.length, mask = capacity - 2, i = hash(key) & mask;; i = (i - 1) & mask) {
long cur = data[i];
if (cur == key) {
data[i + 1] = value;
return;
} else if (cur == EMPTY) {
data[i] = key;
data[i + 1] = value;
if (++size > capacity >> 2) {
this.data = resize(data, capacity << 1);
}
return;
}
}
}
void delete(long key) {
if (key == EMPTY) {
throw new IllegalArgumentException();
}
long data[] = this.data;
for (int capacity = data.length, mask = capacity - 2, i = hash(key) & mask;; i = (i - 1) & mask) {
long cur = data[i];
if (cur == key) {
for (int j = i;;) {
cur = data[j = (j - 1) & mask];
if (cur == EMPTY) {
data[i] = EMPTY;
--size;
return;
}
int k = hash(cur) & mask;
if ((k >= i) ^ (k < j) ^ (i < j)) {
data[i] = cur;
data[i + 1] = data[j + 1];
i = j;
}
}
} else if (cur == EMPTY) {
return;
}
}
}
void expand(int newCapacity) {
long data[] = this.data;
int oldCapacity = data.length;
if (oldCapacity >> 2 < newCapacity) {
this.data = resize(data, Integer.highestOneBit(newCapacity - 1) << 3);
}
}
void shrink() {
long data[] = this.data;
int oldCapacity = data.length;
if (oldCapacity > 4 && oldCapacity >> 3 >= size) {
this.data = resize(data, max(Integer.highestOneBit(size - 1) << 3, 4));
}
}
static class Iterator {
final long data[];
int position = -2;
Iterator(long data[]) {
this.data = data;
advance();
}
boolean hasNext() {
return position < data.length;
}
long getKey() {
return data[position];
}
long getValue() {
return data[position + 1];
}
void advance() {
do {
position += 2;
} while (position < data.length && data[position] == EMPTY);
}
}
Iterator iterator() {
return new Iterator(data);
}
}
static int cnt = 0, vals[] = new int[200000], prevs[][] = new int[20][200000];
static LongLongMap fwd = new LongLongMap();
static int extend(int cur, int val) {
long key = (cur & 0xffffffffL) | ((long) val << 32);
long res = fwd.get(key, -1);
if (res >= 0) {
return (int) res;
}
int r = cnt++;
vals[r] = val;
prevs[0][r] = cur;
for (int i = 1; i < 20; i++) {
prevs[i][r] = cur = cur < 0 ? -1 : prevs[i - 1][cur];
}
fwd.set(key, r);
return r;
}
static int compare(int length, int a, int b) {
if (length == 0) {
return 0;
}
for (int i = 31 - Integer.numberOfLeadingZeros(length - 1); i >= 0; i--) {
if (prevs[i][a] != prevs[i][b]) {
a = prevs[i][a];
b = prevs[i][b];
}
}
return Integer.compare(vals[a], vals[b]);
}
static class Token implements Comparable<Token> {
final int id, len, head, tail, val;
Token(int id, int len, int head, int tail, int val) {
this.id = id;
this.len = len;
this.head = head;
this.tail = tail;
this.val = val;
}
static final int p10[] = {1, 10, 100, 1000, 10000, 100000, 1000000};
static final int MOD = 1000000007;
Token append(int v, int id) {
int l = 0, p = 1;
for (; p <= v; p *= 10) {
++l;
}
int nHead, nTail;
if (len / 9 == (len + l) / 9) {
nHead = head;
nTail = tail * p + v;
} else {
int ll = (len + l) / 9 * 9;
nHead = extend(head, tail * p10[ll - len] + v / p10[len + l - ll]);
nTail = v % p10[len + l - ll];
}
return new Token(id, len + l, nHead, nTail, (int) (((long) val * p + v) % MOD));
}
public int compareTo(Token o) {
if (len != o.len) {
return len - o.len;
}
int r = compare(len / 9, head, o.head);
if (r != 0) {
return r;
}
if (tail != o.tail) {
return Integer.compare(tail, o.tail);
}
return id - o.id;
}
}
static void solve() throws Exception {
int n = scanInt(), m = scanInt();
IntList edges[] = new IntList[n];
for (int i = 0; i < n; i++) {
edges[i] = new IntList();
}
for (int i = 0; i < m; i++) {
int a = scanInt() - 1, b = scanInt() - 1;
edges[a].push(b);
edges[a].push(i + 1);
edges[b].push(a);
edges[b].push(i + 1);
}
Token toks[] = new Token[n];
toks[0] = new Token(0, 0, -1, 0, 0);
PriorityQueue<Token> q = new PriorityQueue<>();
q.add(toks[0]);
boolean processed[] = new boolean[n];
do {
Token tok = q.remove();
int cur = tok.id;
if (processed[cur]) {
continue;
}
processed[cur] = true;
IntList cEdges = edges[cur];
for (int i = 0; i < cEdges.size; i += 2) {
int next = cEdges.data[i], nextE = cEdges.data[i + 1];
Token tNext = tok.append(nextE, next);
if (toks[next] == null || tNext.compareTo(toks[next]) < 0) {
toks[next] = tNext;
q.add(tNext);
}
}
} while (!q.isEmpty());
for (int i = 1; i < n; i++) {
out.println(toks[i].val);
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
4b92f199b382c13ca6748ed2ed718de0
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.UncheckedIOException;
import java.util.List;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
FKoalaAndNotebook solver = new FKoalaAndNotebook();
solver.solve(1, in, out);
out.close();
}
}
static class FKoalaAndNotebook {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int m = in.readInt();
Node[] nodes = new Node[n + 1];
for (int i = 1; i <= n; i++) {
nodes[i] = new Node();
nodes[i].id = i;
}
DigitBase base = new DigitBase(10);
for (int i = 1; i <= m; i++) {
Node a = nodes[in.readInt()];
Node b = nodes[in.readInt()];
Edge e = new Edge();
e.a = a;
e.b = b;
e.len = i;
a.next.add(e);
b.next.add(e);
}
TreeSet<Node> set = new TreeSet<>((a, b) -> {
int ans = Trie.compare(a.t, b.t);
if (ans == 0) {
ans = a.id - b.id;
}
return ans;
});
nodes[1].t = new Trie();
Trie inf = new Trie(nodes[1].t, 10);
inf.depth = 1000000;
for (int i = 2; i <= n; i++) {
nodes[i].t = inf;
}
set.add(nodes[1]);
while (!set.isEmpty()) {
Node head = set.pollFirst();
for (Edge e : head.next) {
Node node = e.other(head);
Trie trie = Trie.insert(head.t, e.len);
if (Trie.compare(node.t, trie) <= 0) {
continue;
}
set.remove(node);
node.t = trie;
set.add(node);
}
}
for (int i = 2; i <= n; i++) {
out.println(nodes[i].t.r);
}
}
}
static class LongList implements Cloneable {
private int size;
private int cap;
private long[] data;
private static final long[] EMPTY = new long[0];
public LongList(int cap) {
this.cap = cap;
if (cap == 0) {
data = EMPTY;
} else {
data = new long[cap];
}
}
public LongList(LongList list) {
this.size = list.size;
this.cap = list.cap;
this.data = Arrays.copyOf(list.data, size);
}
public LongList() {
this(0);
}
public void ensureSpace(int req) {
if (req > cap) {
while (cap < req) {
cap = Math.max(cap + 10, 2 * cap);
}
data = Arrays.copyOf(data, cap);
}
}
private void checkRange(int i) {
if (i < 0 || i >= size) {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(long x) {
ensureSpace(size + 1);
data[size++] = x;
}
public void addAll(long[] x, int offset, int len) {
ensureSpace(size + len);
System.arraycopy(x, offset, data, size, len);
size += len;
}
public void addAll(LongList list) {
addAll(list.data, 0, list.size);
}
public long tail() {
checkRange(0);
return data[size - 1];
}
public long[] toArray() {
return Arrays.copyOf(data, size);
}
public String toString() {
return Arrays.toString(toArray());
}
public boolean equals(Object obj) {
if (!(obj instanceof LongList)) {
return false;
}
LongList other = (LongList) obj;
return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1);
}
public int hashCode() {
int h = 1;
for (int i = 0; i < size; i++) {
h = h * 31 + Long.hashCode(data[i]);
}
return h;
}
public LongList clone() {
LongList ans = new LongList();
ans.addAll(this);
return ans;
}
}
static class Trie {
int depth;
int c;
int r;
Trie[] next = new Trie[10];
Trie[] jump = new Trie[21];
static Modular mod = new Modular(1e9 + 7);
public Trie() {
}
public Trie(Trie p, int c) {
depth = p.depth + 1;
this.c = c;
jump[0] = p;
r = mod.valueOf(p.r * 10L + c);
for (int i = 0; jump[i] != null; i++) {
jump[i + 1] = jump[i].jump[i];
}
}
public static Trie insert(Trie root, int digit) {
if (digit == 0) {
return root;
}
root = insert(root, digit / 10);
int tail = digit % 10;
if (root.next[tail] == null) {
root.next[tail] = new Trie(root, tail);
}
return root.next[tail];
}
public static int compare(Trie a, Trie b) {
if (a.depth != b.depth) {
return a.depth - b.depth;
}
if (a == b) {
return 0;
}
Trie lca = lca(a, b);
a = gotoDepth(a, lca.depth + 1);
b = gotoDepth(b, lca.depth + 1);
return a.c - b.c;
}
public static Trie lca(Trie a, Trie b) {
if (a.depth > b.depth) {
Trie tmp = a;
a = b;
b = tmp;
}
b = gotoDepth(b, a.depth);
if (a == b) {
return a;
}
for (int i = 20; i >= 0; i--) {
if (a.jump[i] == b.jump[i]) {
continue;
}
a = a.jump[i];
b = b.jump[i];
}
return a.jump[0];
}
public static Trie gotoDepth(Trie t, int d) {
if (t.depth == d) {
return t;
}
int log = CachedLog2.floorLog(t.depth - d);
return gotoDepth(t.jump[log], d);
}
public String toString() {
return jump[0] == null ? "" : jump[0].toString() + c;
}
}
static class Node {
List<Edge> next = new ArrayList<>();
Trie t;
int id;
}
static class DigitBase {
private long[] pow;
private long base;
public DigitBase(long base) {
if (base <= 1) {
throw new IllegalArgumentException();
}
this.base = base;
LongList ll = new LongList(64);
ll.add(1);
while (!DigitUtils.isMultiplicationOverflow(ll.tail(), base, Long.MAX_VALUE)) {
ll.add(ll.tail() * base);
}
pow = ll.toArray();
}
}
static class Modular {
int m;
public Modular(int m) {
this.m = m;
}
public Modular(long m) {
this.m = (int) m;
if (this.m != m) {
throw new IllegalArgumentException();
}
}
public Modular(double m) {
this.m = (int) m;
if (this.m != m) {
throw new IllegalArgumentException();
}
}
public int valueOf(long x) {
x %= m;
if (x < 0) {
x += m;
}
return (int) x;
}
public String toString() {
return "mod " + m;
}
}
static class CachedLog2 {
private static final int BITS = 16;
private static final int LIMIT = 1 << BITS;
private static final byte[] CACHE = new byte[LIMIT];
static {
int b = 0;
for (int i = 0; i < LIMIT; i++) {
while ((1 << (b + 1)) <= i) {
b++;
}
CACHE[i] = (byte) b;
}
}
public static int floorLog(int x) {
return x < LIMIT ? CACHE[x] : (BITS + CACHE[x >>> BITS]);
}
}
static class DigitUtils {
private DigitUtils() {
}
public static boolean isMultiplicationOverflow(long a, long b, long limit) {
if (limit < 0) {
limit = -limit;
}
if (a < 0) {
a = -a;
}
if (b < 0) {
b = -b;
}
if (a == 0 || b == 0) {
return false;
}
//a * b > limit => a > limit / b
return a > limit / b;
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class SequenceUtils {
public static boolean equal(long[] a, int al, int ar, long[] b, int bl, int br) {
if ((ar - al) != (br - bl)) {
return false;
}
for (int i = al, j = bl; i <= ar; i++, j++) {
if (a[i] != b[j]) {
return false;
}
}
return true;
}
}
static class Edge {
Node a;
Node b;
int len;
Node other(Node x) {
return a == x ? b : a;
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
85ce1ef2c35a1c351d3619b87529ffa0
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.UncheckedIOException;
import java.util.List;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
FKoalaAndNotebook solver = new FKoalaAndNotebook();
solver.solve(1, in, out);
out.close();
}
}
static class FKoalaAndNotebook {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int m = in.readInt();
Node[] nodes = new Node[n + 1];
for (int i = 1; i <= n; i++) {
nodes[i] = new Node();
nodes[i].id = i;
}
DigitBase base = new DigitBase(10);
for (int i = 1; i <= m; i++) {
Node a = nodes[in.readInt()];
Node b = nodes[in.readInt()];
Edge e = new Edge();
e.a = a;
e.b = b;
e.len = i;
a.next.add(e);
b.next.add(e);
}
StringTree tree = new StringTree(0, 9, 1000000);
TreeSet<Node> set = new TreeSet<>((a, b) -> {
int ans = StringTree.TrieNode.compare(a.t, b.t);
if (ans == 0) {
ans = a.id - b.id;
}
return ans;
});
nodes[1].t = tree.getRoot();
StringTree.TrieNode inf = tree.getMax();
for (int i = 2; i <= n; i++) {
nodes[i].t = inf;
}
set.add(nodes[1]);
while (!set.isEmpty()) {
Node head = set.pollFirst();
for (Edge e : head.next) {
Node node = e.other(head);
StringTree.TrieNode trie = insert(tree, head.t, e.len);
if (StringTree.TrieNode.compare(node.t, trie) <= 0) {
continue;
}
set.remove(node);
node.t = trie;
set.add(node);
}
}
for (int i = 2; i <= n; i++) {
out.println(nodes[i].t.r);
}
}
public StringTree.TrieNode insert(StringTree tree, StringTree.TrieNode root, int digit) {
if (digit == 0) {
return root;
}
root = insert(tree, root, digit / 10);
return tree.insert(root, digit % 10);
}
}
static class DigitUtils {
private DigitUtils() {
}
public static boolean isMultiplicationOverflow(long a, long b, long limit) {
if (limit < 0) {
limit = -limit;
}
if (a < 0) {
a = -a;
}
if (b < 0) {
b = -b;
}
if (a == 0 || b == 0) {
return false;
}
//a * b > limit => a > limit / b
return a > limit / b;
}
}
static class Modular {
int m;
public Modular(int m) {
this.m = m;
}
public Modular(long m) {
this.m = (int) m;
if (this.m != m) {
throw new IllegalArgumentException();
}
}
public Modular(double m) {
this.m = (int) m;
if (this.m != m) {
throw new IllegalArgumentException();
}
}
public int valueOf(long x) {
x %= m;
if (x < 0) {
x += m;
}
return (int) x;
}
public String toString() {
return "mod " + m;
}
}
static class LongList implements Cloneable {
private int size;
private int cap;
private long[] data;
private static final long[] EMPTY = new long[0];
public LongList(int cap) {
this.cap = cap;
if (cap == 0) {
data = EMPTY;
} else {
data = new long[cap];
}
}
public LongList(LongList list) {
this.size = list.size;
this.cap = list.cap;
this.data = Arrays.copyOf(list.data, size);
}
public LongList() {
this(0);
}
public void ensureSpace(int req) {
if (req > cap) {
while (cap < req) {
cap = Math.max(cap + 10, 2 * cap);
}
data = Arrays.copyOf(data, cap);
}
}
private void checkRange(int i) {
if (i < 0 || i >= size) {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(long x) {
ensureSpace(size + 1);
data[size++] = x;
}
public void addAll(long[] x, int offset, int len) {
ensureSpace(size + len);
System.arraycopy(x, offset, data, size, len);
size += len;
}
public void addAll(LongList list) {
addAll(list.data, 0, list.size);
}
public long tail() {
checkRange(0);
return data[size - 1];
}
public long[] toArray() {
return Arrays.copyOf(data, size);
}
public String toString() {
return Arrays.toString(toArray());
}
public boolean equals(Object obj) {
if (!(obj instanceof LongList)) {
return false;
}
LongList other = (LongList) obj;
return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1);
}
public int hashCode() {
int h = 1;
for (int i = 0; i < size; i++) {
h = h * 31 + Long.hashCode(data[i]);
}
return h;
}
public LongList clone() {
LongList ans = new LongList();
ans.addAll(this);
return ans;
}
}
static class Edge {
Node a;
Node b;
int len;
Node other(Node x) {
return a == x ? b : a;
}
}
static class DigitBase {
private long[] pow;
private long base;
public DigitBase(long base) {
if (base <= 1) {
throw new IllegalArgumentException();
}
this.base = base;
LongList ll = new LongList(64);
ll.add(1);
while (!DigitUtils.isMultiplicationOverflow(ll.tail(), base, Long.MAX_VALUE)) {
ll.add(ll.tail() * base);
}
pow = ll.toArray();
}
}
static class CachedLog2 {
private static final int BITS = 16;
private static final int LIMIT = 1 << BITS;
private static final byte[] CACHE = new byte[LIMIT];
static {
int b = 0;
for (int i = 0; i < LIMIT; i++) {
while ((1 << (b + 1)) <= i) {
b++;
}
CACHE[i] = (byte) b;
}
}
public static int ceilLog(int x) {
int ans = floorLog(x);
if ((1 << ans) < x) {
ans++;
}
return ans;
}
public static int floorLog(int x) {
return x < LIMIT ? CACHE[x] : (BITS + CACHE[x >>> BITS]);
}
}
static class SequenceUtils {
public static boolean equal(long[] a, int al, int ar, long[] b, int bl, int br) {
if ((ar - al) != (br - bl)) {
return false;
}
for (int i = al, j = bl; i <= ar; i++, j++) {
if (a[i] != b[j]) {
return false;
}
}
return true;
}
}
static class StringTree {
static Modular mod = new Modular(1e9 + 7);
int l;
int r;
int log;
StringTree.TrieNode root;
StringTree.TrieNode max;
StringTree.TrieNode min;
public StringTree.TrieNode getRoot() {
return root;
}
public StringTree.TrieNode getMax() {
return max;
}
public StringTree(int l, int r, int maxDepth) {
if (maxDepth == Integer.MAX_VALUE) {
maxDepth--;
}
this.l = l;
this.r = r;
log = CachedLog2.ceilLog(maxDepth + 1);
root = newTrieNode();
max = newTrieNode(root, 0);
min = newTrieNode(root, 0);
max.depth = maxDepth + 1;
min.depth = -1;
}
private StringTree.TrieNode newTrieNode() {
StringTree.TrieNode ans = new StringTree.TrieNode();
ans.next = new StringTree.TrieNode[r - l + 1];
ans.jump = new StringTree.TrieNode[log + 1];
return ans;
}
public StringTree.TrieNode newTrieNode(StringTree.TrieNode p, int c) {
StringTree.TrieNode node = newTrieNode();
node.depth = p.depth + 1;
node.value = c;
node.jump[0] = p;
node.r = mod.valueOf(p.r * 10L + c);
for (int i = 0; node.jump[i] != null; i++) {
node.jump[i + 1] = node.jump[i].jump[i];
}
return node;
}
public StringTree.TrieNode insert(StringTree.TrieNode root, int digit) {
if (root.next[digit - l] == null) {
root.next[digit - l] = newTrieNode(root, digit);
}
return root.next[digit - l];
}
public static class TrieNode {
int depth;
int value;
StringTree.TrieNode[] next;
StringTree.TrieNode[] jump;
int r;
public static int compare(StringTree.TrieNode a, StringTree.TrieNode b) {
if (a.depth != b.depth) {
return a.depth - b.depth;
}
if (a == b) {
return 0;
}
StringTree.TrieNode lca = lca(a, b);
a = gotoDepth(a, lca.depth + 1);
b = gotoDepth(b, lca.depth + 1);
return a.value - b.value;
}
public static StringTree.TrieNode lca(StringTree.TrieNode a, StringTree.TrieNode b) {
if (a.depth > b.depth) {
StringTree.TrieNode tmp = a;
a = b;
b = tmp;
}
b = gotoDepth(b, a.depth);
if (a == b) {
return a;
}
for (int i = 20; i >= 0; i--) {
if (a.jump[i] == b.jump[i]) {
continue;
}
a = a.jump[i];
b = b.jump[i];
}
return a.jump[0];
}
public static StringTree.TrieNode gotoDepth(StringTree.TrieNode t, int d) {
if (t.depth == d) {
return t;
}
int log = CachedLog2.floorLog(t.depth - d);
return gotoDepth(t.jump[log], d);
}
public String toString() {
return jump[0] == null ? "" : jump[0].toString() + value;
}
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class Node {
List<Edge> next = new ArrayList<>();
StringTree.TrieNode t;
int id;
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
c8bbfd474159c306c891a22885b41119
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class CFContest {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = true;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
long lInf = (long) 1e18;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve1();
}
public void solve1() {
int n = io.readInt();
int m = io.readInt();
Node[] nodes = new Node[1 + n];
Tries tries = new Tries();
for (int i = 1; i <= n; i++) {
nodes[i] = new Node();
nodes[i].id = i;
nodes[i].which = Tries.Node.inf;
}
for (int i = 1; i <= m; i++) {
Node a = nodes[io.readInt()];
Node b = nodes[io.readInt()];
Edge e = new Edge();
e.a = a;
e.b = b;
e.number = i;
a.edge.add(e);
b.edge.add(e);
}
TreeSet<Node> set = new TreeSet<>((a, b) -> a.which == b.which ? a.id - b.id : Tries.Node.cmp(a.which, b.which));
nodes[1].which = tries.root;
for (int i = 1; i <= n; i++) {
set.add(nodes[i]);
}
while (!set.isEmpty()) {
Node head = set.pollFirst();
for (Edge e : head.edge) {
Node node = e.a == head ? e.b : e.a;
Tries.Node dist = tries.get(head.which, e.number);
if (Tries.Node.cmp(dist, node.which) >= 0) {
continue;
}
set.remove(node);
node.which = dist;
set.add(node);
}
}
for (int i = 2; i <= n; i++) {
io.cache.append(nodes[i].which.prefix).append('\n');
}
}
}
public static class Tries {
private Node root = new Node();
private Node inf = new Node();
public Node get(Node since, int c) {
Node trace = since;
int v = 1;
while (v * 10 <= c) {
v *= 10;
}
while (v != 0) {
trace = trace.get(c / v);
c %= v;
v /= 10;
}
return trace;
}
private static class Node {
Node[] children = new Node[10];
Node[] bl = new Node[20];
static Node inf = new Node();
static{
Arrays.fill(inf.children, inf);
}
int depth;
static int mod = (int) 1e9 + 7;
int prefix;
int c;
private Node() {
}
public Node climb(int depth) {
int diff = this.depth - depth;
Node trace = this;
for (int i = 0; diff >= (1 << i); i++) {
int bit = (1 << i);
if ((bit & diff) > 0) {
trace = trace.bl[i];
}
}
return trace;
}
public static int cmp(Node a, Node b) {
if (a == inf && b == inf) {
return 0;
}
if (a == inf) {
return 1;
}
if (b == inf) {
return -1;
}
if (a == b) {
return 0;
}
if (a.depth != b.depth) {
return a.depth - b.depth;
}
int step = 19;
while (step >= 0) {
if (a.bl[step] == null ||
a.bl[step] == b.bl[step]) {
} else {
a = a.bl[step];
b = b.bl[step];
}
step--;
}
return a.c - b.c;
}
public Node get(int i) {
if (children[i] == null) {
children[i] = new Node();
children[i].c = i;
children[i].prefix = (int) (((long) prefix * 10 + i) % mod);
children[i].depth = depth + 1;
children[i].bl[0] = this;
for (int j = 0; j < 19 && children[i].bl[j] != null; j++) {
children[i].bl[j + 1] = children[i].bl[j].bl[j];
}
}
return children[i];
}
}
}
public static class Edge {
Node a;
Node b;
int number;
}
public static class Node {
List<Edge> edge = new ArrayList<>();
Tries.Node which;
int id;
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder(20 << 20);
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 8);
private byte[] buf = new byte[1 << 20];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() {
try {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasMore() {
skipBlank();
return next != -1;
}
}
public static class Debug {
private boolean allowDebug;
public Debug(boolean allowDebug) {
this.allowDebug = allowDebug;
}
public void assertTrue(boolean flag) {
if (!allowDebug) {
return;
}
if (!flag) {
fail();
}
}
public void fail() {
throw new RuntimeException();
}
public void assertFalse(boolean flag) {
if (!allowDebug) {
return;
}
if (flag) {
fail();
}
}
private void outputName(String name) {
System.out.print(name + " = ");
}
public void debug(String name, int x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, long x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, double x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, int[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, long[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, double[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, Object x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, Object... x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.deepToString(x));
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
9cdecc0edd1ed7f6ff1b347759066271
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.security.SecureRandom;
import java.util.List;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Collections;
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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
List<Integer>[] graph;
int vertices;
void addEdge(int from, int to, String s) {
for (int i = 0; i < s.length(); i++) {
if (i + 1 == s.length()) {
addOne(from, to, s.charAt(i) - '0');
} else {
int newV = vertices++;
addOne(from, newV, s.charAt(i) - '0');
from = newV;
}
}
}
private void addOne(int from, int to, int charAt) {
graph[from].add((charAt << 24) + to);
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt();
graph = Utils.listArray(n + 40 * m);
vertices = n;
for (int i = 1; i <= m; i++) {
int from = in.nextInt() - 1, to = in.nextInt() - 1;
String s = Integer.toString(i);
addEdge(from, to, s);
addEdge(to, from, s);
}
for (int i = 0; i < n; i++) {
if (graph[i].size() > 1) {
Collections.sort(graph[i]);
}
}
int mod = 1000000007;
int[] dist = new int[graph.length];
Arrays.fill(dist, -1);
dist[0] = 0;
int[] q = new int[graph.length];
int head = 0, tail = 0;
q[tail++] = 0;
int[] val = new int[graph.length];
Arrays.fill(val, -1);
val[0] = 0;
int[] hash = new int[graph.length];
Arrays.fill(hash, -1);
hash[0] = 0;
int prime = BigInteger.probablePrime(30, new SecureRandom()).intValue();
int[] lastChar = new int[graph.length];
Arrays.fill(lastChar, 10);
int[] count = new int[10];
while (head < tail) {
int endSegment = head;
int start = q[head];
while (endSegment < tail && hash[q[endSegment]] == hash[start]) {
endSegment++;
}
Arrays.fill(count, 0);
for (int pos = head; pos < endSegment; pos++) {
int cur = q[pos];
for (int t = 0; t < graph[cur].size(); t++) {
int edge = graph[cur].get(t);
int c = edge >> 24;
int v = edge & ((1 << 24) - 1);
if (dist[v] == -1) {
if (lastChar[v] < 10) {
count[lastChar[v]]--;
}
lastChar[v] = Math.min(lastChar[v], c);
count[lastChar[v]]++;
}
}
}
for (int pos = 1; pos < 10; pos++) {
count[pos] += count[pos - 1];
}
int added = count[9];
for (int pos = head; pos < endSegment; pos++) {
int cur = q[pos];
for (int t = 0; t < graph[cur].size(); t++) {
int edge = graph[cur].get(t);
int v = edge & ((1 << 24) - 1);
if (dist[v] == -1) {
dist[v] = dist[start] + 1;
val[v] = (int) ((10L * val[start] + lastChar[v]) % mod);
hash[v] = (int) ((10L * hash[start] + lastChar[v]) % prime);
--count[lastChar[v]];
q[tail + count[lastChar[v]]] = v;
}
}
}
head = endSegment;
tail += added;
}
for (int i = 1; i < n; i++) {
out.println(val[i]);
}
}
}
static class Utils {
public static <T> List<T>[] listArray(int size) {
List<T>[] result = new List[size];
for (int i = 0; i < size; i++) {
result[i] = new ArrayList<>();
}
return result;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public FastScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (st == null || !st.hasMoreElements()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
4215a263031b78ffde022555202cd155
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
//package round584;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Queue;
public class F {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni();
int[] from = new int[10*m+2];
int[] to = new int[10*m+2];
int[] ws = new int[10*m+2];
int p = 0;
int gen = n;
for(int i = 0;i < m;i++){
int f = ni()-1, t = ni()-1;
char[] s = ("" + (i+1)).toCharArray();
int cur = f;
for(int j = 0;j < s.length;j++){
char c = s[j];
from[p] = cur;
to[p] = j == s.length-1 ? t : gen++;
ws[p] = c-'0';
cur = to[p];
p++;
}
cur = t;
for(int j = 0;j < s.length;j++){
char c = s[j];
from[p] = cur;
to[p] = j == s.length-1 ? f : gen++;
ws[p] = c-'0';
cur = to[p];
p++;
}
}
int[][][] g = packWD(gen, from, to, ws, p);
for(int[][] row : g){
Arrays.sort(row, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[1] - b[1];
}
});
}
int[] ds = new int[gen];
int I = 99999999;
Arrays.fill(ds, I);
ds[0] = 0;
int mod = 1000000007;
long[] vals = new long[gen];
Queue<Queue<Integer>> qs = new ArrayDeque<>();
{
Queue<Integer> q = new ArrayDeque<>();
q.add(0);
qs.add(q);
}
while(!qs.isEmpty()){
Queue<Integer> q = qs.poll();
List<int[]> ns = new ArrayList<>();
while(!q.isEmpty()){
int cur = q.poll();
for(int[] e : g[cur]){
if(ds[e[0]] == I){
ns.add(new int[]{e[0], e[1], cur});
}
}
}
Collections.sort(ns, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[1] - b[1];
}
});
int pre = -1;
Queue<Integer> pack = new ArrayDeque<>();
for(int[] e : ns){
if(ds[e[0]] == I){
if(e[1] != pre && !pack.isEmpty()){
qs.add(pack);
pack = new ArrayDeque<>();
}
pre = e[1];
ds[e[0]] = ds[e[2]] + 1;
vals[e[0]] = (vals[e[2]] * 10 + e[1]) % mod;
pack.add(e[0]);
}
}
if(!pack.isEmpty()){
qs.add(pack);
}
}
for(int i = 1;i < n;i++){
out.println(vals[i]);
}
}
public static int[][][] packWD(int n, int[] from, int[] to, int[] w){ return packWD(n, from, to, w, from.length); }
public static int[][][] packWD(int n, int[] from, int[] to, int[] w, int sup)
{
int[][][] g = new int[n][][];
int[] p = new int[n];
for(int i = 0;i < sup;i++)p[from[i]]++;
for(int i = 0;i < n;i++)g[i] = new int[p[i]][2];
for(int i = 0;i < sup;i++){
--p[from[i]];
g[from[i]][p[from[i]]][0] = to[i];
g[from[i]][p[from[i]]][1] = w[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
851ca62400ed2a464e924d632db884ce
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class F extends PrintWriter {
final long mod = 1_000_000_000 + 7;
int k = 20;
class Node implements Comparable<Node> {
final int len;
final long hash;
final int id;
final int d;
final Node[] p = new Node[k];
public Node(Node p, int d, int id) {
this.id = id;
this.d = d;
if (p == null) {
Arrays.fill(this.p, this);
this.len = 0;
this.hash = d;
} else {
this.len = p.len + 1;
this.hash = (((p.hash * 10) % mod) + d) % mod;
this.p[0] = p;
for (int h = 1; h < k; h++) {
this.p[h] = this.p[h - 1].p[h - 1];
}
}
}
@Override
public int compareTo(Node node) {
return compare(this, node);
}
}
int compare(Node a, Node b) {
int cmp = compareD(a, b);
// println(cmp == Long.compare(a.hash, b.hash));
return cmp;
}
int compareD(Node a, Node b) {
if (a.len != b.len) {
return Integer.compare(a.len, b.len);
}
if (a.len == 1) {
return Integer.compare(a.d, b.d);
}
if (a.hash == b.hash) {
return 0;
}
for (int h = k - 1; h >= 0; h--) {
if (a.p[h].hash != b.p[h].hash) {
return compare(a.p[h], b.p[h]);
}
}
return Integer.compare(a.d, b.d);
}
Node get(Node cur, int id, int num) {
int dd = 1;
int dn = num;
while (dn > 0) {
dd *= 10;
dn /= 10;
}
// println(num);
dd /= 10;
while (dd > 0) {
int h = num / dd;
// println(h + " " + num + " " + dd);
cur = new Node(cur, h, id);
num -= h * dd;
dd /= 10;
}
return cur;
}
class Edge {
final int id, u, v;
public Edge(int id, int u, int v) {
this.id = id;
this.u = u;
this.v = v;
}
int to(int from) {
if (from == u) {
return v;
} else {
return u;
}
}
}
void run() {
int n = nextInt();
int m = nextInt();
Node[] min = new Node[n + 1];
List<Edge>[] g = new List[n + 1];
for (int i = 0; i <= n; i++) {
g[i] = new ArrayList<Edge>();
}
for (int i = 1; i <= m; i++) {
int u = nextInt(), v = nextInt();
Edge edge = new Edge(i, u, v);
g[u].add(edge);
g[v].add(edge);
}
Node s = min[1] = new Node(null, 0, 1);
PriorityQueue<Node> queue = new PriorityQueue<>();
queue.add(s);
while (!queue.isEmpty()) {
Node node = queue.poll();
if (min[node.id].compareTo(node) == 0) {
for (Edge edge : g[node.id]) {
int v = edge.to(node.id);
Node tmp = get(node, v, edge.id);
// println(v + " " + tmp.hash);
if (min[v] == null || min[v].compareTo(tmp) > 0) {
min[v] = tmp;
queue.add(tmp);
}
}
}
}
// println(Arrays.toString(min));
for (int i = 2; i <= n; i++) {
println(min[i].hash);
}
}
void skip() {
while (hasNext()) {
next();
}
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
String next() {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
int[] nextArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException err) {
return null;
}
}
public F(OutputStream outputStream) {
super(outputStream);
}
static BufferedReader reader;
static StringTokenizer tokenizer = new StringTokenizer("");
static Random rnd = new Random();
static boolean OJ;
public static void main(String[] args) throws IOException {
OJ = System.getProperty("ONLINE_JUDGE") != null;
F solution = new F(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(F.class.getName() + ".txt")));
long timeout = System.currentTimeMillis();
while (solution.hasNext()) {
solution.run();
solution.println();
solution.println("----------------------------------");
}
solution.println("time: " + (System.currentTimeMillis() - timeout));
}
solution.close();
reader.close();
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
c825b61c5e35ff9ddb9ced0262937397
|
train_001.jsonl
|
1568466300
|
Koala Land consists of $$$m$$$ bidirectional roads connecting $$$n$$$ cities. The roads are numbered from $$$1$$$ to $$$m$$$ by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city $$$1$$$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo $$$10^9+7$$$. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
static final int MODULO = (int) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n0 = in.nextInt();
int m0 = in.nextInt();
int[] first = new int[10 * (n0 + 12 * m0)];
int[] next = new int[2 * (7 * m0)];
int[] dest = new int[2 * (7 * m0)];
int n = n0;
int m = 0;
Arrays.fill(first, -1);
for (int i = 1; i <= m0; ++i) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
for (int iter = 0; iter < 2; ++iter) {
int tmp = i;
int cur = iter == 0 ? x : y;
while (tmp > 0) {
int d = tmp % 10;
tmp /= 10;
int nxt = (tmp == 0 ? (iter == 0 ? y : x) : n++);
dest[m] = cur;
next[m] = first[10 * nxt + d];
first[10 * nxt + d] = m;
++m;
cur = nxt;
}
}
}
int[] dist = new int[n];
Arrays.fill(dist, -1);
dist[0] = 0;
int[] queue = new int[n + 1];
boolean[] blockStart = new boolean[n + 1];
int qt = 0;
int qh = 1;
blockStart[0] = true;
queue[0] = 0;
blockStart[1] = true;
while (qt < qh) {
int qm = qt + 1;
while (qm < qh && !blockStart[qm]) ++qm;
for (int d = 0; d < 10; ++d) {
for (int i = qt; i < qm; ++i) {
int cur = queue[i];
int e = first[cur * 10 + d];
while (e >= 0) {
int b = dest[e];
if (dist[b] < 0) {
dist[b] = (int) ((dist[cur] * (long) 10 + d) % MODULO);
queue[qh++] = b;
}
e = next[e];
}
}
blockStart[qh] = true;
}
qt = qm;
}
for (int i = 1; i < n0; ++i) {
if (dist[i] < 0) throw new RuntimeException();
out.println(dist[i]);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["11 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11", "12 19\n1 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 11\n11 12\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10", "12 14\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n10 11\n11 12\n1 3\n1 4\n1 10"]
|
2 seconds
|
["1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\n345678826", "1\n12\n13\n14\n15\n16\n17\n18\n19\n1210\n121011", "1\n12\n13\n134\n1345\n13456\n1498\n149\n14\n1410\n141011"]
| null |
Java 8
|
standard input
|
[
"graphs",
"shortest paths",
"data structures",
"dfs and similar",
"trees",
"strings"
] |
b70b03c888876e8979a7990c22229194
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$), the number of cities and the number of roads, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between cities $$$x_i$$$ and $$$y_i$$$. It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
| 2,600 |
Print $$$n - 1$$$ integers, the answer for every city except for the first city. The $$$i$$$-th integer should be equal to the smallest number he could have written for destination $$$i+1$$$. Since this number may be large, output its remainder modulo $$$10^9+7$$$.
|
standard output
| |
PASSED
|
79eeb7034b27e53261679b6b24fc87e6
|
train_001.jsonl
|
1505653500
|
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer s = new StringTokenizer(br.readLine());
int n=Integer.parseInt(s.nextToken());
HashMap<String,Integer>hm=new HashMap<>();
HashSet<String>ts=new HashSet<>();
for(int i=0;i<n;i++) {
s = new StringTokenizer(br.readLine());
String str=s.nextToken();
for(int ii=0;ii<9;ii++) {
for(int jj=ii+1;jj<=9;jj++) {
String st=str.substring(ii, jj);
if(!hm.containsKey(st)) {
hm.put(st, i);
ts.add(st);
}else {
if(hm.get(st)!=i)
ts.remove(st);
}
}
}
}
ArrayList<String>l=new ArrayList<>();
for(String ns:ts) {
l.add(ns);
}
Collections.sort(l,(a,b)->a.length()-b.length());
// for(String ns:l)
// pw.println(ns+" "+hm.get(ns));
int count=0;
String ans[]=new String[n];
for(String ns:l) {
if(count==n)
break;
if(ans[hm.get(ns)]==null) {
ans[hm.get(ns)]=ns;
count++;
}
}
for(String as:ans) {
pw.println(as);
}
pw.close();
}
}
|
Java
|
["3\n123456789\n100000000\n100123456", "4\n123456789\n193456789\n134567819\n934567891"]
|
4 seconds
|
["9\n000\n01", "2\n193\n81\n91"]
| null |
Java 11
|
standard input
|
[
"data structures",
"implementation",
"brute force",
"strings"
] |
37d906de85f173aca2a9a3559cbcf7a3
|
The first line contains single integer n (1ββ€βnββ€β70000) β the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
| 1,600 |
Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.
|
standard output
| |
PASSED
|
e23d3ead57d34c19110484c00fce2511
|
train_001.jsonl
|
1505653500
|
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
ArrayList<String>list=new ArrayList<>();
for(int i=0;i<n;i++) {
list.add(s.next());
}
HashSet<String>hs=new HashSet<>();
HashMap<String ,Integer>hm=new HashMap<>();
for(int l=0;l<n;l++) {
String str=list.get(l);
for (int i = 0; i < 9; i++) {
for (int j = i+1; j <= 9; j++) {
String tmp=str.substring(i, j);
if(hm.containsKey(tmp)&&hm.get(tmp)!=l)
hm.remove(tmp);
if(!hs.contains(tmp))
hm.put(tmp, l);
hs.add(tmp);
}
}
}
ArrayList<String>l=new ArrayList<>();
for(String val:hm.keySet()) {
l.add(val);
}
Collections.sort(l,new Comparator<String>() {
@Override
public int compare(String s1,String s2) {
return s1.length()-s2.length();
}
});
// for(String ans:l) {
// System.out.println(ans+" "+hm.get(ans));
// }
//
//
//
// System.out.println(l.size());
int count=0;
String ans[]=new String[n];
boolean visited[]=new boolean[n];
for(String val:l) {
if(count==n)
break;
if(!visited[hm.get(val)]) {
ans[hm.get(val)]=val;
count++;
visited[hm.get(val)]=true;
}
}
for(int i=0;i<n;i++) {
System.out.println(ans[i]);
}
}
}
|
Java
|
["3\n123456789\n100000000\n100123456", "4\n123456789\n193456789\n134567819\n934567891"]
|
4 seconds
|
["9\n000\n01", "2\n193\n81\n91"]
| null |
Java 11
|
standard input
|
[
"data structures",
"implementation",
"brute force",
"strings"
] |
37d906de85f173aca2a9a3559cbcf7a3
|
The first line contains single integer n (1ββ€βnββ€β70000) β the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
| 1,600 |
Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.
|
standard output
| |
PASSED
|
4e68049968b6a6ec575562cada8a563a
|
train_001.jsonl
|
1505653500
|
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer s = new StringTokenizer(br.readLine());
int n=Integer.parseInt(s.nextToken());
HashMap<String,Integer>hm=new HashMap<>();
HashSet<String>ts=new HashSet<>();
for(int i=0;i<n;i++) {
s = new StringTokenizer(br.readLine());
String str=s.nextToken();
for(int ii=0;ii<9;ii++) {
for(int jj=ii+1;jj<=9;jj++) {
String st=str.substring(ii, jj);
if(!hm.containsKey(st)) {
hm.put(st, i);
ts.add(st);
}else {
if(hm.get(st)!=i)
ts.remove(st);
}
}
}
}
ArrayList<String>l=new ArrayList<>();
for(String ns:ts) {
l.add(ns);
}
Collections.sort(l,(a,b)->a.length()-b.length());
// for(String ns:l)
// pw.println(ns+" "+hm.get(ns));
int count=0;
String ans[]=new String[n];
boolean visited[]=new boolean[n];
for(String ns:l) {
if(count==n)
break;
if(!visited[hm.get(ns)]) {
ans[hm.get(ns)]=ns;
count++;
visited[hm.get(ns)]=true;
}
}
for(String as:ans) {
pw.println(as);
}
//
pw.close();
//
pw.close();
}
}
|
Java
|
["3\n123456789\n100000000\n100123456", "4\n123456789\n193456789\n134567819\n934567891"]
|
4 seconds
|
["9\n000\n01", "2\n193\n81\n91"]
| null |
Java 11
|
standard input
|
[
"data structures",
"implementation",
"brute force",
"strings"
] |
37d906de85f173aca2a9a3559cbcf7a3
|
The first line contains single integer n (1ββ€βnββ€β70000) β the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
| 1,600 |
Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.
|
standard output
| |
PASSED
|
fe5ab2981febdb6d66e3218fb80eb7a1
|
train_001.jsonl
|
1505653500
|
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
|
256 megabytes
|
//package Coding;
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
ArrayList<String>list=new ArrayList<>();
for(int i=0;i<n;i++) {
list.add(s.next());
}
HashSet<String>hs=new HashSet<>();
HashMap<String ,Integer>hm=new HashMap<>();
for(int l=0;l<n;l++) {
String str=list.get(l);
for (int i = 0; i < 9; i++) {
for (int j = i+1; j <= 9; j++) { ///approach ye h ki ismai hamne sare substring nikal liye aur jo different substring unko set mai daal liya
String tmp=str.substring(i, j);
if(hm.containsKey(tmp)&&hm.get(tmp)!=l) //ye condition islye lagayi agr jo substring h woh same string mai se aarha h to uske ek bari to add karna padega
///jase 1000000 000 ismai aayega lekin ismai repeat hoga to hame add karna padega ek bari to
hm.remove(tmp);
if(!hs.contains(tmp))
hm.put(tmp, l);
hs.add(tmp);
}
}
}
ArrayList<String>l=new ArrayList<>();
for(String val:hm.keySet()) {
l.add(val);
}
Collections.sort(l,new Comparator<String>() {
@Override
public int compare(String s1,String s2) {
return s1.length()-s2.length();
}
});
// for(String ans:l) {
// System.out.println(ans+" "+hm.get(ans));
// }
//
//
//
// System.out.println(l.size());
int count=0;
String ans[]=new String[n];
boolean visited[]=new boolean[n];
for(String val:l) {
if(count==n)
break;
if(!visited[hm.get(val)]) {
ans[hm.get(val)]=val;
count++;
visited[hm.get(val)]=true;
}
}
for(int i=0;i<n;i++) {
System.out.println(ans[i]);
}
}
}
|
Java
|
["3\n123456789\n100000000\n100123456", "4\n123456789\n193456789\n134567819\n934567891"]
|
4 seconds
|
["9\n000\n01", "2\n193\n81\n91"]
| null |
Java 11
|
standard input
|
[
"data structures",
"implementation",
"brute force",
"strings"
] |
37d906de85f173aca2a9a3559cbcf7a3
|
The first line contains single integer n (1ββ€βnββ€β70000) β the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
| 1,600 |
Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.
|
standard output
| |
PASSED
|
a7b071f509c53a2be4ab757c04bf8c9c
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Map.Entry;
public class Main implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final int MI = (int) 1e9;
static final long ML = (long) 1e18;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new Main(), "persefone", 1 << 32).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
int n = in.nextInt();
int k = in.nextInt();
int[] open = new int[n];
int[] close = new int[n];
for (int i = 0; i < n; i++) {
open[i] = in.nextInt();
close[i] = in.nextInt() + 1;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(open[i], map.getOrDefault(open[i], 0) + 1);
map.put(close[i], map.getOrDefault(close[i], 0) - 1);
}
int[] both = map.entrySet().stream().mapToInt(Entry::getKey).toArray();
Arrays.sort(both);
int prev = 0;
for (int i = 0; i < both.length; i++) {
prev += map.get(both[i]);
map.put(both[i], prev);
}
long[] factorial = IntegerUtils.factorial(n, MOD);
long ans = 0;
prev = both[0];
int before = map.get(prev);
for (int i = 1; i < both.length; i++) {
int cur = both[i];
if (before >= k) {
ans += IntegerUtils.Cnk(factorial, before, k, MOD) * (cur - prev) % MOD;
if (ans >= MOD) {
ans -= MOD;
}
}
prev = cur;
before = map.get(prev);
}
printf(ans);
}
static class IntegerUtils {
public static long[] factorial(int n, long mod) {
long[] f = new long[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = f[i - 1] * i % mod;
}
return f;
}
public static long modPow(long base, long exponent, long mod) {
if (exponent == 0) return 1;
long m = modPow(base, exponent >> 1, mod);
return exponent % 2 == 0 ? m * m % mod : m * m % mod * base % mod;
}
public static long Cnk(long[] factorial, int n, int k, long mod) {
return factorial[n] * modPow(factorial[k], mod - 2, mod) % mod * modPow(factorial[n - k], mod - 2, mod) % mod;
}
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void flush() {
out.flush();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Reader(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
boolean isReady() throws IOException {
return br.ready();
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
| |
PASSED
|
bf480244d923f3234838e3d8c7cc7791
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Map.Entry;
public class Main implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final int MI = (int) 1e9;
static final long ML = (long) 1e18;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new Main(), "persefone", 1 << 32).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
int n = in.nextInt();
int k = in.nextInt();
int[] open = new int[n];
int[] close = new int[n];
for (int i = 0; i < n; i++) {
open[i] = in.nextInt();
close[i] = in.nextInt() + 1;
}
Arrays.sort(open);
Arrays.sort(close);
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(open[i]);
set.add(close[i]);
map.put(open[i], map.getOrDefault(open[i], 0) + 1);
map.put(close[i], map.getOrDefault(close[i], 0) - 1);
}
int[] both = set.stream().mapToInt(Integer::intValue).toArray();
Arrays.sort(both);
int prev = 0;
for (int i = 0; i < both.length; i++) {
prev += map.get(both[i]);
map.put(both[i], prev);
}
long[] factorial = IntegerUtils.factorial(n, MOD);
long ans = 0;
prev = both[0];
int before = map.get(prev);
for (int i = 1; i < both.length; i++) {
int cur = both[i];
if (before >= k) {
ans += IntegerUtils.Cnk(factorial, before, k, MOD) * (cur - prev) % MOD;
if (ans >= MOD) {
ans -= MOD;
}
}
prev = cur;
before = map.get(prev);
}
printf(ans);
}
static class IntegerUtils {
public static long[] factorial(int n, long mod) {
long[] f = new long[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = f[i - 1] * i % mod;
}
return f;
}
public static long modPow(long base, long exponent, long mod) {
if (exponent == 0) return 1;
long m = modPow(base, exponent >> 1, mod);
return exponent % 2 == 0 ? m * m % mod : m * m % mod * base % mod;
}
public static long Cnk(long[] factorial, int n, int k, long mod) {
return factorial[n] * modPow(factorial[k], mod - 2, mod) % mod * modPow(factorial[n - k], mod - 2, mod) % mod;
}
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void flush() {
out.flush();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Reader(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
boolean isReady() throws IOException {
return br.ready();
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
| |
PASSED
|
b76b13d0749d52ec390ac613e965a0aa
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class E {
static final long MODULO = 1000000007;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
Pair[] events = new Pair[2*n];
for(int i=0;i<n;i++){
events[2*i] = new Pair(in.nextInt(), -1); //-1 for in
events[2*i+1] = new Pair(in.nextInt(), 1); //1 for out
}
Arrays.sort(events, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.v1 != o2.v1) return o1.v1 - o2.v1;
return o1.v2 - o2.v2;
}
});
int[] p = new int[n+1];
int cur = 0;
int i = 0;
int prev = 0;
while(i<2*n){
// INV: cur - how many overlapping segments for [prev, events[i].v1)
if(events[i].v2 == -1){
if(cur>0) p[cur] += events[i].v1 - prev;
cur++; // if no equal segments, equivalent to cur++, indicates one more seg overlap
prev = events[i].v1;
} else {
if(cur>0) p[cur] += events[i].v1 - prev+1;
cur--; // ending brace, decrement the seg overlap cnt
prev = events[i].v1 + 1;
}
i++;
}
// for(i=0;i<n+1;i++){
// out.print(p[i] + " ");
// }
long ans = 0;
long comb = 1;
for(i=k;i<=n;i++){
ans = (ans + comb * p[i]) % MODULO;
comb = nextComb(comb, (long)i+1, (long)k);
}
out.println(ans);
out.flush();
}
private static long nextComb(long comb, long p, long k) {
return (((comb * p) % MODULO) * invmod(p-k, MODULO)) % MODULO;
}
private static long invmod(long p, long modu) {
long g0 = modu;
long g1 = p;
long u0=1; long v0=0;
long u1=0; long v1=1;
while (g1>0){
long y=g0 /g1;
long g2=g0-y*g1;
long u2=u0-y*u1;
long v2=v0-y*v1;
g0=g1;
g1=g2;
u0=u1;
u1=u2;
v0=v1;
v1=v2;
}
if (v0>=0){
return v0;
}else{
return v0 + modu;
}
}
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());
}
}
}
class Pair{
int v1;
int v2;
public Pair(int v1, int v2) {
super();
this.v1 = v1;
this.v2 = v2;
}
boolean equal(Pair p){
return this.v1 == p.v1 && this.v2 == p.v2;
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
| |
PASSED
|
6810b19d8385de2cc04b69e9f5f863e0
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class E {
static final long MODULO = 1000000007;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
int k = in.nextInt();
Pair[] events = new Pair[2*n];
for(int i=0;i<(2*n);i++){
events[i++] = new Pair(in.nextInt(), -1); //-1 for in
events[i] = new Pair(in.nextInt(), 1); //1 for out
}
Arrays.sort(events, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.v1 != o2.v1) return o1.v1 - o2.v1;
return o1.v2 - o2.v2;
}
});
int[] p = new int[n+1];
int cur = 0;
int i = 0;
for (i = 0; i < (2*n); ++i) {
// INV: cur - how many overlapping segments for [prev, events[i].v1)
int prev = (i == 0) ? 0 : ((events[i-1].v2 == 1) ? events[i-1].v1 + 1 : events[i-1].v1);
if(events[i].v2 == -1){
p[cur] += events[i].v1 - prev;
cur++; // if no equal segments, equivalent to cur++, indicates one more seg overlap
} else {
p[cur] += events[i].v1 - prev+1;
cur--; // ending brace, decrement the seg overlap cnt
}
}
// for(i=0;i<n+1;i++){
// out.print(p[i] + " ");
// }
long ans = 0;
long comb = 1;
for(i=k;i<=n;i++){
ans = (ans + comb * p[i]) % MODULO;
comb = nextComb(comb, (long)i+1, (long)k);
}
out.println(ans);
out.flush();
}
private static long nextComb(long comb, long p, long k) {
return (((comb * p) % MODULO) * invmod(p-k, MODULO)) % MODULO;
}
private static long invmod(long p, long modu) {
long g0 = modu;
long g1 = p;
long u0=1; long v0=0;
long u1=0; long v1=1;
while (g1>0){
long y=g0 /g1;
long g2=g0-y*g1;
long u2=u0-y*u1;
long v2=v0-y*v1;
g0=g1;
g1=g2;
u0=u1;
u1=u2;
v0=v1;
v1=v2;
}
if (v0>=0){
return v0;
}else{
return v0 + modu;
}
}
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());
}
}
}
class Pair{
int v1;
int v2;
public Pair(int v1, int v2) {
super();
this.v1 = v1;
this.v2 = v2;
}
boolean equal(Pair p){
return this.v1 == p.v1 && this.v2 == p.v2;
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
| |
PASSED
|
87cc00704b1ea0f19dda78b60e06227e
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Comparator;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Igor Kraskevich
*/
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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
final long MOD = 1000 * 1000 * 1000 + 7;
final int N = 200 * 1000 + 10;
long[] f;
long binPow(long x, long n) {
long res = 1;
while (n > 0) {
if (n % 2 == 1)
res = res * x % MOD;
x = x * x % MOD;
n /= 2;
}
return res;
}
long inverse(long x) {
return binPow(x, MOD - 2);
}
void prec() {
f = new long[N];
f[0] = 1;
for (int i = 1; i < N; i++)
f[i] = f[i - 1] * i % MOD;
}
long cnk(int n, int k) {
long res = f[n];
res = res * inverse(f[k]) % MOD;
return res * inverse(f[n - k]) % MOD;
}
class Event {
int x;
int delta;
Event(int x, int delta) {
this.x = x;
this.delta = delta;
}
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
prec();
int n = in.nextInt();
int k = in.nextInt();
ArrayList<Event> events = new ArrayList<>();
for (int i = 0; i < n; i++) {
int l = in.nextInt();
int r = in.nextInt() + 1;
events.add(new Event(l, 1));
events.add(new Event(r, -1));
}
Collections.sort(events, new Comparator<Event>() {
public int compare(Event o1, Event o2) {
return Integer.compare(o1.x, o2.x);
}
});
int open = 0;
long res = 0;
for (int i = 0; i < events.size() - 1; i++) {
Event e = events.get(i);
open += e.delta;
int len = events.get(i + 1).x - e.x;
if (open >= k && len != 0) {
long cur = cnk(open, k);
cur = cur * len % MOD;
res = (res + cur) % MOD;
}
}
out.println(res);
}
}
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
| |
PASSED
|
24b977e1c74754abd3ca4ae264c48b66
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.util.*;
import java.io.*;
// Main
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
TreeMap<Integer, Integer> map = new TreeMap<>();
long mod = 1000000007;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
int n = in.nextInt();
int k = in.nextInt();
long[] fac = new long[n + 1];
long[] ifac = new long[n + 1];
fac[0] = 1;
ifac[0] = 1;
for (int i = 1; i <= n; i++) {
fac[i] = fac[i-1] * i % mod;
ifac[i] = ifac[i-1] * inv(i) % mod;
if(test)System.out.println(i + " " + fac[i] + " " + ifac[i]);
}
long ans = 0;
for (int i = 0; i < n; i++) {
int l = in.nextInt();
int r = in.nextInt() + 1;
if (map.containsKey(l)) map.put(l, map.get(l) + 1);
else map.put(l, 1);
if (map.containsKey(r)) map.put(r, map.get(r) - 1);
else map.put(r, -1);
}
int nCover = 0;
boolean first = true;
int xleft = -1;
int vleft = 0;
for (int x : map.keySet()) {
nCover += map.get(x);
if (first) {
first = false;
xleft = x;
vleft = nCover;
}else {
if(test)System.out.println("x = " + x + ", vleft = " + vleft + ", xleft = " + xleft + ", nCover = " + nCover);
if (nCover != vleft) {
//this node will be added for choose(nCover, k) times
if (vleft >= k) {
int len = x - xleft;
if(test)System.out.println("Add len = " + len);
ans += fac[vleft] * ifac[k] % mod * ifac[vleft-k] % mod * len % mod;
if (ans >= mod) ans -= mod;
}
vleft = nCover;
xleft = x;
}
}
}
System.out.println(ans);
}
long a = 1, b = 1;
private long inv(long x) {
extended_gcd(x, mod);
return (a % mod + mod) % mod;
}
private void extended_gcd(long x, long y) {
if (y == 0) {
a = 1;
b = 0;
return;
}
long q = x / y;
long r = x - q * y;
extended_gcd(y, r);
long tmp_b = b;
long tmp_a = a;
a = tmp_b;
b = tmp_a - a * q;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//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)
{
return "";
//e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
| |
PASSED
|
3d6fde4507769ccd4ec12bbdc7a047aa
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.util.*;
import java.io.*;
// Main
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
class Event implements Comparable<Event> {
int x, val;
public Event(int x, int val) {
this.x=x;
this.val = val;
}
public int compareTo(Event other) {
return Integer.compare(x, other.x);
}
}
long mod = 1000000007;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
int n = in.nextInt();
int k = in.nextInt();
long[] fac = new long[n + 1];
long[] ifac = new long[n + 1];
fac[0] = 1;
ifac[0] = 1;
for (int i = 1; i <= n; i++) {
fac[i] = fac[i-1] * i % mod;
ifac[i] = ifac[i-1] * inv(i) % mod;
if(test)System.out.println(i + " " + fac[i] + " " + ifac[i]);
}
int nEvents = n * 2;
long ans = 0;
Event[] events = new Event[nEvents];
for (int i = 0; i < n; i++) {
int l = in.nextInt();
int r = in.nextInt() + 1;
events[i*2] = new Event(l, 1);
events[i*2 + 1] = new Event(r, -1);
}
Arrays.sort(events);
int nCover = 0;
boolean first = true;
int xleft = -1;
int vleft = -1;
for (int i = 0; i < nEvents; ) {
int x = events[i].x;
nCover += events[i].val;
++i;
while (i < nEvents && events[i].x == x) {
nCover += events[i++].val;
}
if (first) {
first = false;
vleft = nCover;
xleft = x;
}else {
if(test)System.out.println("x = " + x + ", vleft = " + vleft + ", xleft = " + xleft + ", nCover = " + nCover);
if (nCover != vleft) {
//this node will be added for choose(nCover, k) times
if (vleft >= k) {
int len = x - xleft;
if(test)System.out.println("Add len = " + len);
ans += fac[vleft] * ifac[k] % mod * ifac[vleft-k] % mod * len % mod;
if (ans >= mod) ans -= mod;
}
vleft = nCover;
xleft = x;
}
}
}
System.out.println(ans);
}
long a = 1, b = 1;
private long inv(long x) {
extended_gcd(x, mod);
return (a % mod + mod) % mod;
}
private void extended_gcd(long x, long y) {
if (y == 0) {
a = 1;
b = 0;
return;
}
long q = x / y;
long r = x - q * y;
extended_gcd(y, r);
long tmp_b = b;
long tmp_a = a;
a = tmp_b;
b = tmp_a - a * q;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//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)
{
return "";
//e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
| |
PASSED
|
e9390bbc80778a095373f50db58deeb9
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l,βr])β=βrβ-βlβ+β1 to be the number of integer points in the segment [l,βr] with lββ€βr (say that ). You are given two integers n and k and n closed intervals [li,βri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109β+β7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class E {
static final long MODULO = 1000000007;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
Pair[] events = new Pair[2*n];
for(int i=0;i<n;i++){
events[2*i] = new Pair(in.nextInt(), -1); //-1 for in
events[2*i+1] = new Pair(in.nextInt(), 1); //1 for out
}
Arrays.sort(events, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.v1 != o2.v1) return o1.v1 - o2.v1;
return o1.v2 - o2.v2;
}
});
int[] p = new int[n+1];
int cur = 0;
int i = 0;
int prev = 0;
while(i<2*n){
int temp = i;
while(i<2*n-1 && events[i+1].equal(events[i])) i++;
if(events[i].v2 == -1){
if(cur>0) p[cur] += events[i].v1 - prev;
cur += i - temp + 1;
prev = events[i].v1;
} else {
if(cur>0) p[cur] += events[i].v1 - prev+1;
cur -= i - temp + 1;
prev = events[i].v1 + 1;
}
i++;
}
// for(i=0;i<n+1;i++){
// out.print(p[i] + " ");
// }
long ans = 0;
long comb = 1;
for(i=k;i<=n;i++){
ans = (ans + comb * p[i]) % MODULO;
comb = nextComb(comb, (long)i+1, (long)k);
}
out.println(ans);
out.flush();
}
private static long nextComb(long comb, long p, long k) {
return (((comb * p) % MODULO) * invmod(p-k, MODULO)) % MODULO;
}
private static long invmod(long p, long modu) {
long g0 = modu;
long g1 = p;
long u0=1; long v0=0;
long u1=0; long v1=1;
while (g1>0){
long y=g0 /g1;
long g2=g0-y*g1;
long u2=u0-y*u1;
long v2=v0-y*v1;
g0=g1;
g1=g2;
u0=u1;
u1=u2;
v0=v1;
v1=v2;
}
if (v0>=0){
return v0;
}else{
return v0 + modu;
}
}
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());
}
}
}
class Pair{
int v1;
int v2;
public Pair(int v1, int v2) {
super();
this.v1 = v1;
this.v2 = v2;
}
boolean equal(Pair p){
return this.v1 == p.v1 && this.v2 == p.v2;
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2β+β1β+β2β=β5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000)Β β the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li,βri (β-β109ββ€βliββ€βriββ€β109), describing i-th segment bounds.
| 2,000 |
Print one integer numberΒ β the answer to Mike's problem modulo 1000000007 (109β+β7) in the only line.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.