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
|
b021a77858c71881472cfff91def6391
|
train_001.jsonl
|
1600526100
|
An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.
|
256 megabytes
|
import java.io.PrintWriter;
import java.util.*;
public class Main extends PrintWriter {
public Main() {
super(System.out);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Main main = new Main();
int n = s.nextInt();
while (n-- > 0) {
main.MainPrint(s);
}
main.flush();
}
List<int[]> list;
List<Integer>[] ans1;
private void MainPrint(Scanner s) {
int n = s.nextInt();
int nCopy = n;
list = new ArrayList<>();
int[] append;
for (int i = 2; i*i <= nCopy; i++) {
if(nCopy%i == 0){
append = new int[]{i,0};
list.add(append);
while (nCopy%i==0){
append[1]++;
nCopy/=i;
}
}
}
if(nCopy!=1) list.add(new int[]{nCopy,1});
// println(list.size());
StringBuilder ans = new StringBuilder();
if (list.size() == 1){
for (int i = 1; i <= list.get(0)[1]; i++) {
if(ans.length()!=0) ans.append(' ');
ans.append((int)Math.pow(list.get(0)[0],i));
}
println(ans);
println(0);
}else if(list.size() == 2){
if(list.get(0)[1]>=2){
ans.append(list.get(0)[0]*list.get(1)[0]);
for (int i = 1; i <= list.get(0)[1]; i++) {
for (int j = 0; j <= list.get(1)[1]; j++){
if((i == 1 || i == 2) && j ==1) continue;
ans.append(' ');
ans.append((int)Math.pow(list.get(0)[0],i)*(int)Math.pow(list.get(1)[0],j));
}
}
ans.append(' ');
ans.append(list.get(0)[0]*list.get(1)[0]*list.get(0)[0]);
for (int i = 1; i <= list.get(1)[1]; i++) {
ans.append(' ');
ans.append((int)Math.pow(list.get(1)[0],i));
}
println(ans);
println(0);
}else if (list.get(1)[1]>=2){
ans.append(list.get(0)[0]*list.get(1)[0]);
for (int i = 1; i <= list.get(0)[1]; i++) {
for (int j = 0; j <= list.get(1)[1]; j++){
if(i == 1 && (j == 1 || j == 2)) continue;
ans.append(' ');
ans.append((int)Math.pow(list.get(0)[0],i)*(int)Math.pow(list.get(1)[0],j));
}
}
ans.append(' ');
ans.append(list.get(0)[0]*list.get(1)[0]*list.get(1)[0]);
for (int i = 1; i <= list.get(1)[1]; i++) {
ans.append(' ');
ans.append((int)Math.pow(list.get(1)[0],i));
}
println(ans);
println(0);
}else {
ans.append(list.get(0)[0]*list.get(1)[0]);
ans.append(' ');
ans.append(list.get(0)[0]);
ans.append(' ');
ans.append(list.get(1)[0]);
println(ans);
println(1);
}
}else {
ans1 = new List[list.size()];
for (int i = 0; i < ans1.length; i++) ans1[i] = new LinkedList<>();
for (int i = 2; i*i <= n; i++){
if(n%i==0){
add(i);
if(i*i!=n){
add(n/i);
}
}
}
add(n);
for (int i = 0; i<ans1.length;i++){
if(ans.length()!=0) ans.append(' ');
ans.append(list.get(i==0?ans1.length-1:i-1)[0]*list.get(i)[0]);
for (int j:ans1[i]) {
ans.append(' ');
ans.append(j);
}
}
println(ans);
println(0);
}
}
private void add(int i) {
int p = 0;
while(true) {
if (i % list.get(p)[0] == 0 && i != list.get(p)[0] * list.get(p == list.size() - 1 ? 0 : p + 1)[0] && i != list.get(p)[0] * list.get(p == 0 ? list.size() - 1 : p - 1)[0]) {
ans1[p].add(i);
break;
} else if (i % list.get(p)[0] != 0 && p != list.size() - 1) {
p++;
}else {
break;
}
}
}
}
|
Java
|
["3\n6\n4\n30"]
|
1 second
|
["2 3 6 \n1\n2 4 \n0\n2 30 6 3 15 5 10 \n0"]
|
NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation",
"number theory",
"math"
] |
406f8f662d2013d87b36dacca663bef5
|
The first line contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \le n \le 10^9)$$$ — the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
| 2,100 |
For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them.
|
standard output
| |
PASSED
|
23e8c1f551ce264ac4e608829fa4b3cd
|
train_001.jsonl
|
1600526100
|
An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main{
static long mod = 1000000007;
static class Point{
int x, y;
Point(int nx, int ny){
x = nx; y = ny;
}
}
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int q = pint(in);
for(; q > 0; q--) {
int n = pint(in);
ArrayList<Integer> fact = fact(n);
ArrayList<Integer> ans = new ArrayList<Integer>();
Collections.sort(fact);
if(fact.size() == 3) {
for(int i : fact) {
System.out.print(i);
System.out.print(' ');
}
System.out.println();
if(gcd(fact.get(0), fact.get(1)) == 1) {System.out.println(1);}
else{System.out.println(0);}
continue;
}
int s = fact.size();
int k = s - 1;
boolean[] u = new boolean[s];
u[k] = true;
ans.add(fact.get(k));
for(int i = 1; i < s; i++) {
int j;
for(j = 0; j < s; j++) {
if(u[j] || gcd(fact.get(j), fact.get(k)) == 1) {continue;}
break;
}
u[j] = true;
ans.add(fact.get(j));
k = j;
}
StringBuilder sb = new StringBuilder();
for(int i : ans) {
sb.append(i);
sb.append(' ');
}
System.out.println(sb);
System.out.println(0);
}
}
static int gcd(int a, int b) {
if(a == 0) {return b;}
return gcd(b % a, a);
}
static ArrayList<Integer> fact(int k){
int sqrt = (int)(Math.sqrt(k));
ArrayList<Point> f = new ArrayList<Point>();
int k1 = k;
for(int i = 2; i <= sqrt; i++) {
if(k1 % i != 0) {continue;}
int t = 0;
while(k1 % i == 0) {
k1 /= i;
t++;
}
f.add(new Point(i,t));
}
if(k1 != 1) {f.add(new Point(k1, 1));}
return all_fact(f, 0, 1);
}
static ArrayList<Integer> all_fact(ArrayList<Point> f, int ix, int v){
if(ix == f.size()) {
ArrayList<Integer> r = new ArrayList<Integer>();
if(v == 1) {return r;}
r.add(v);
return r;
}
int t = 1;
ArrayList<Integer> r = new ArrayList<Integer>();
for(int i = 0; i <= f.get(ix).y; i++) {
r.addAll(all_fact(f, ix + 1, v * t));
t *= f.get(ix).x;
}
return r;
}
static int pint(BufferedReader in) throws IOException {return Integer.parseInt(in.readLine());}
static int pint(StringTokenizer st) {return Integer.parseInt(st.nextToken());}
}
|
Java
|
["3\n6\n4\n30"]
|
1 second
|
["2 3 6 \n1\n2 4 \n0\n2 30 6 3 15 5 10 \n0"]
|
NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation",
"number theory",
"math"
] |
406f8f662d2013d87b36dacca663bef5
|
The first line contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \le n \le 10^9)$$$ — the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
| 2,100 |
For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them.
|
standard output
| |
PASSED
|
60455b9fd8a3b16d3c4e8234c72031b9
|
train_001.jsonl
|
1600526100
|
An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
long MAX = 100000L, MOD = 1000000007L, INF = (long) 1e18;
void solve(int TC) throws Exception {
int n = ni();
TreeSet<Integer> factors = new TreeSet<>();
for(int i=2;i*i<=n;++i) {
if(n%i!=0) continue;
factors.add(i);
if(i!=n/i) factors.add(n/i);
}
factors.add(n);
int N = factors.size();
int[] ans = new int[N];
ans[0] = factors.pollFirst();
for(int i = 1; i < N; i++) {
int g = ans[i-1];
for(int it: factors) {
if(gcd(g, it) == 1) continue;
ans[i] = it;
break;
}
factors.remove(ans[i]);
}
for(int i: ans) p(i+" ");pn("");
pn(gcd(ans[0], ans[N-1]) == 1 ? 1 : 0);
}
boolean TestCases = true;
public static void main(String[] args) throws Exception { new Main().run(); }
long gcd(long a, long b) { return (b==0) ? a : gcd(b,a%b); }
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
int T = TestCases ? ni() : 1;
for(int t=1;t<=T;t++) solve(t);
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
void p(Object o) { out.print(o); }
void pn(Object o) { out.println(o); }
void pni(Object o) { out.println(o);out.flush(); }
double PI = 3.141592653589793238462643383279502884197169399;
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();
}
}
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();
}
}
double nd() { return Double.parseDouble(ns()); }
char nc() { return (char)skip(); }
int BUF_SIZE = 1024 * 8;
byte[] inbuf = new byte[BUF_SIZE];
int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b); b = readByte();
} return sb.toString();
}
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);
}
void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["3\n6\n4\n30"]
|
1 second
|
["2 3 6 \n1\n2 4 \n0\n2 30 6 3 15 5 10 \n0"]
|
NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation",
"number theory",
"math"
] |
406f8f662d2013d87b36dacca663bef5
|
The first line contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \le n \le 10^9)$$$ — the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
| 2,100 |
For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them.
|
standard output
| |
PASSED
|
aefa4a494c735d15ffcfce439b7b9280
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static ArrayList<Integer> adj[];
static char color[];
static boolean b[],visited[],possible;
static Map<Integer,HashSet<Integer>> s;
static int totalnodes,colored;
static int count[];
static long sum[];
public static void main(String[] args) throws IOException {
in=new InputReader(System.in);
w=new PrintWriter(System.out);
int n=in.nextInt();
ArrayList<String> od=new ArrayList<String>();
ArrayList<String> nw=new ArrayList<String>();
for(int i=0;i<n;i++)
{
String[] s=in.nextLine().split(" ");
od.add(s[0]);
nw.add(s[1]);
}
for(int i=nw.size()-1;i>=0;i--)
{
for(int j=0;j<od.size();j++)
{
if(nw.get(i).equals(od.get(j)))
{
nw.set(i,nw.get(j));
od.remove(j);
nw.remove(j);
//i--;
}
}
}
w.println(od.size());
for(int i=0;i<od.size();i++)
w.println(od.get(i)+" "+nw.get(i));
w.close();
}
static InputReader in;
static PrintWriter w;
public static void seive(long n){
b = new boolean[(int) (n+1)];
Arrays.fill(b, true);
for(int i = 2;i*i<=n;i++){
if(b[i]){
sum[i]=count[i];
// System.out.println(sum[i]+" wf");
for(int p = 2*i;p<=n;p+=i){
b[p] = false;
sum[i]+=count[p];
//System.out.println(sum[i]);
}
}
}
}
static class Pair implements Comparable<Pair> {
int edge;
int c;
public Pair(){
}
public Pair(int u, int v) {
this.edge = u;
this.c= v;
}
public int compareTo(Pair other) {
return 0;
}
/*public String toString() {
return "[u=" + u + ", v=" + v + "]";
}*/
}
static class Node2{
Node2 left = null;
Node2 right = null;
Node2 parent = null;
int data;
}
//binaryStree
static class BinarySearchTree{
Node2 root = null;
int height = 0;
int max = 0;
int cnt = 1;
ArrayList<Integer> parent = new ArrayList<Integer>();
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
public void insert(int x){
Node2 n = new Node2();
n.data = x;
if(root==null){
root = n;
}
else{
Node2 temp = root,temp2 = null;
while(temp!=null){
temp2 = temp;
if(x>temp.data) temp = temp.right;
else temp = temp.left;
}
if(x>temp2.data) temp2.right = n;
else temp2.left = n;
n.parent = temp2;
parent.add(temp2.data);
}
}
public Node2 getSomething(int x, int y, Node2 n){
if(n.data==x || n.data==y) return n;
else if(n.data>x && n.data<y) return n;
else if(n.data<x && n.data<y) return getSomething(x,y,n.right);
else return getSomething(x,y,n.left);
}
public Node2 search(int x,Node2 n){
if(x==n.data){
max = Math.max(max, n.data);
return n;
}
if(x>n.data){
max = Math.max(max, n.data);
return search(x,n.right);
}
else{
max = Math.max(max, n.data);
return search(x,n.left);
}
}
public int getHeight(Node2 n){
if(n==null) return 0;
height = 1+ Math.max(getHeight(n.left), getHeight(n.right));
return height;
}
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static String rev(String s)
{
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}
static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
public static long max(long x, long y, long z){
if(x>=y && x>=z) return x;
if(y>=x && y>=z) return y;
return z;
}
static int[] sieve(int n,int[] arr)
{
for(int i=2;i*i<=n;i++)
{
if(arr[i]==0)
{
for(int j=i*2;j<=n;j+=i)
arr[j]=1;
}
}
return arr;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
64e11468536d92dcd11287371db98ec7
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int q = nextInt();
TreeMap<String, String> a = new TreeMap<>();
for (int i = 0; i < q; i++) {
String v = nextToken();
String h = nextToken();
if (!a.containsKey(v))
a.put(h, v);
else {
String b = a.get(v);
a.remove(v);
a.put(h, b);
}
}
System.out.println(a.size());
for(Map.Entry<String, String> i : a.entrySet()){
System.out.println(i.getValue() + " " + i.getKey());
}
}
static BufferedReader br;
static StringTokenizer in = new StringTokenizer("");
static String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong((nextToken()));
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
23b7e4aa1cfb72f00690d9782e3690be
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = nextInt();
TreeMap<String, String> a = new TreeMap<>();
for (int i = 0; i < n; i++) {
String old = next();
String new1 = next();
if (a.containsKey(old)) {
a.put(new1, a.get(old));
a.remove(old);
} else a.put(new1, old);
}
System.out.println(a.size());
for (Map.Entry<String, String> i : a.entrySet()) {
System.out.println(i.getValue() + " " + i.getKey());
}
}
static BufferedReader br;
static StringTokenizer in = new StringTokenizer("");
static String next() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
b46f970cdf9a51be5ab2c773465bf467
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
static HashMap<String, String> map = new HashMap<String, String>();
static String x, y;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok;
int n = parseInt(reader.readLine());
for (int i = 0; i < n; i++) {
tok = new StringTokenizer(reader.readLine());
x = tok.nextToken();
y = tok.nextToken();
if (check()) {
map.put(x, y);
}
}
System.out.println(map.size());
for (String i : map.keySet()) {
System.out.println(i +" "+map.get(i));
}
}
public static boolean check() {
for (String o : map.keySet()) {
if (map.get(o).equals(x)) {
map.put(o, y);
return false;
}
}
return true;
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
65e6908dcfe0f2f55e45d86134ec73fe
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class gibberish {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
int n = sc.nextInt();
String[] first = new String[n];
String[] second = new String[n];
HashMap<String,String> seen1 = new HashMap<String,String>();
HashMap<String,String> seenr = new HashMap<String,String>();
HashSet<String> seen = new HashSet<String>();
for (int k = 0; k < n; k++){
first[k] = sc.next();
second[k] = sc.next();
}
int count = 0;
for (int j = 0; j < n; j++){
if (!seen.contains(second[j]) && !seen.contains(first[j])){
seen.add(first[j]);
seen.add(second[j]);
count++;
seen1.put(first[j], second[j]);
seenr.put(second[j], first[j]);
}else {
if (seen.contains(first[j])){
String orig = seenr.get(first[j]);
seen.add(second[j]);
seenr.put(second[j], orig);
seen1.put(orig, second[j]);
seenr.remove(first[j]);
}
}
}
System.out.println(count);
for (String s: seen1.keySet()){
if (!seen1.get(s).equals(s)){
System.out.println(s+" "+seen1.get(s));
}
}
out.close();
}
public static String in(String n, int k, char c) {
String ret = n.substring(0, k) + c + n.substring(k);
return ret;
}
public static boolean isPal(String n) {
int len = n.length();
for (int k = 0; k < len; k++) {
if (n.charAt(k) != n.charAt(len - k - 1)) {
return false;
}
}
return true;
}
public static class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream in) throws Exception {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer(br.readLine());
}
public String next() throws Exception {
if (st.hasMoreTokens()) {
return st.nextToken();
}
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
40db55124a6996382445bddb7f31772c
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Ibrahim Ali
*/
public class BMishaAndChangingHandles {
/**
* @param args the command line arguments
*/
ArrayList old = new ArrayList<String>();
ArrayList new_pas = new ArrayList<String>();
ArrayList result = new ArrayList<String>();
public ArrayList checkOK(ArrayList old, ArrayList new_pas){
for (int i = 0; i < old.size(); i++) {
String key = String.valueOf(old.get(i));
String value = String.valueOf(new_pas.get(i));
if (!old.contains(value) && !new_pas.contains(key)) {
result.add(key);
result.add(value);
}
for (int j = 0; j < old.size(); j++) {
String key1 = String.valueOf(old.get(j));
String value1 = String.valueOf(new_pas.get(j));
if (value.equals(key1)) {
result.add(key);
result.add(value1);
}
}
}
return result;
}
public static void main(String[] args) {
// TODO code application logic here
int n;
String new_pass , old_pass;
Scanner in = new Scanner(System.in);
ArrayList old = new ArrayList<String>();
ArrayList new_pas = new ArrayList<String>();
ArrayList result = new ArrayList<String>();
n = in.nextInt();
for (int i = 0; i < n ; i++) {
old_pass = in.next();
new_pass = in.next();
if(new_pas.contains(String.valueOf(old_pass))){
int j = new_pas.indexOf(String.valueOf(old_pass));
String newpass = String.valueOf(new_pas.get(j));
String oldpass = String.valueOf(old.get(j));
old.remove(j);
new_pas.remove(j);
old.add(oldpass);
new_pas.add(new_pass);
}
else{
old.add(old_pass);
new_pas.add(new_pass);
}
}
BMishaAndChangingHandles obj = new BMishaAndChangingHandles();
result = obj.checkOK(old, new_pas);
//System.out.println();
System.out.println(result.size()/2);
for (int i = 0; i < result.size() ; i+=2) {
System.out.println(result.get(i) + " " + result.get(i+1));
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
b57ffa33797c2f0c4f8904f80f12de48
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
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.HashMap;
import java.util.StringTokenizer;
public class Main {
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class Pair
{
final String first,second;
Pair(String first,String second)
{
this.first=first;
this.second=second;
}
}
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[] nextSArray() {
String sr[] = null;
try {
sr = br.readLine().trim().split(" ");
} catch (IOException e) {
e.printStackTrace();
}
return sr;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int t1=sc.nextInt();
HashMap<String,String>hm=new HashMap<>();
for(int t=0;t<t1;++t) {
String s[]=sc.nextLine().trim().split(" ");
String a=s[0];
String b=s[1];
boolean found =false;
for(String key :hm.keySet())
{
if(hm.get(key).equals(a))
{ hm.put(key,b);
found=true;
}
}
if(!found)
hm.put(a,b);
}
out.println(hm.size());
for(String key :hm.keySet())
{
out.println(key+" "+hm.get(key));
}
out.close();
}
}
//out.close();
// out.println(al.toString().replaceAll("[\\[|\\]|,]",""));
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
16019d5bc1c8ef0c5f9b68fcc700a478
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
//package javaapplication1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class Main {
public static void main(String[] args) throws IOException{
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new PrintStream(System.out));
//Scanner sc=new Scanner(System.in);
FastScanner in=new FastScanner();
int n=in.nextInt();
Map<String,ArrayList<String>>users=new HashMap<>();
String x,y;
boolean inList;
for (int i = 0; i < n; ++i) {
x=in.nextToken();y=in.nextToken();
inList=false;
for (String k:users.keySet()) {
if(users.get(k).contains(x))
{users.get(k).add(y);inList=true;break;}
}
if(!inList)
{users.put(x, new ArrayList<>());users.get(x).add(y);}
}
System.out.println(users.size());
for (String k:users.keySet()) {
System.out.println(k+" "+users.get(k).get(users.get(k).size()-1));
}
}
public static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(String s)
{
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken()
{
while (st == null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(nextToken());
}
long nextLong()
{
return Long.parseLong(nextToken());
}
double nextDouble()
{
return Double.parseDouble(nextToken());
}
String next()
{
return nextToken();
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
5ee439f17b5df9efb26e84b6b0a305b9
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
//package javaapplication1;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import sun.awt.HKSCS;
public class Main {
public static void main(String[] args) throws IOException{
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new PrintStream(System.out));
//Scanner sc=new Scanner(System.in);
FastScanner in=new FastScanner();
int n=in.nextInt();
Map<String,ArrayList<String>>users=new HashMap<>();
String x,y;
boolean inList;
for (int i = 0; i < n; ++i) {
x=in.nextToken();y=in.nextToken();
inList=false;
for (String k:users.keySet()) {
if(users.get(k).contains(x))
{users.get(k).add(y);inList=true;break;}
}
if(!inList)
{users.put(x, new ArrayList<>());users.get(x).add(y);}
}
System.out.println(users.size());
for (String k:users.keySet()) {
System.out.println(k+" "+users.get(k).get(users.get(k).size()-1));
}
}
public static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(String s)
{
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken()
{
while (st == null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(nextToken());
}
long nextLong()
{
return Long.parseLong(nextToken());
}
double nextDouble()
{
return Double.parseDouble(nextToken());
}
String next()
{
return nextToken();
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
c121cc24063ee4d48c892098a3b57e99
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
//package cf;
import java.util.Scanner;
public class water2 {
public static Scanner cin = new Scanner(System.in);
public static void main(String[] args) {
while(cin.hasNext()) {
int n=cin.nextInt();
String[][] str=new String[n][2];
for(int i=0;i<n;i++) {
str[i][0]=cin.next();
str[i][1]=cin.next();
}
int count=n;
for(int i=0;i<n-1;i++) {
if(str[i][0]!=null) {
for(int j=i+1;j<n;j++) {
if(str[j][0]!=null&&str[j][0].equals(str[i][1])) {
str[i][1]=str[j][1];
str[j][0]=null;
count--;
}
}
}
}
System.out.println(count);
for(int i=0;i<n;i++) {
if(str[i][0]!=null) {
System.out.println(str[i][0]+" "+str[i][1]);
}
}
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
9b8ccdae6f8e4291b0433fede646e56d
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
//package cf;
import java.util.HashMap;
import java.util.Scanner;
public class water2 {
public static Scanner cin = new Scanner(System.in);
public static void main(String[] args) {
while(cin.hasNext()) {
int n=cin.nextInt();
HashMap<String,String> map=new HashMap<String, String>();
for(int i=0;i<n;i++) {
String olds=cin.next();
String news=cin.next();
boolean flag=false;
for(String key:map.keySet()) {
if(map.get(key).equals(olds)) {
map.put(key, news);
flag=true;
}
}
if(!flag) {
map.put(olds, news);
}
}
System.out.println(map.size());
for(String key:map.keySet()) {
System.out.println(key+" "+map.get(key));
}
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
e4c1c53b22a3ff6d7a241ecafebb029f
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Misha_and_Changing_Handles {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int q=scanner.nextInt();
HashMap<String, String> hMap=new HashMap<>();
HashMap<String, String> hMap2=new HashMap<>();
HashSet<String> set=new HashSet<>();
String value[]=new String[q];
String key[]=new String[q];
for(int i=0;i<q;i++)
{
String a=scanner.next();
String b=scanner.next();
value[i]=b;
key[i]=a;
hMap.put(a, b);
}
for(int i=0;i<q;i++)
{
if(set.contains(key[i]))continue;
String t=hMap.get(key[i]);
String z=t;
t=hMap.get(t);
if(t==null)
{
hMap2.put(key[i], z);
}
else
{
while(t!=null)
{
set.add(z);
z=t;
t=hMap.get(t);
}
hMap2.put(key[i], z);
}
}
int len=hMap2.size();
System.out.println(len);
for(String s:hMap2.keySet())
{
System.out.println(s+" "+hMap2.get(s));
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
6ad08c80d94c58ac8142f0d7c9220223
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.lang.Math;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
Map<String, String> map = new TreeMap<String, String>();
while(n-->0){
String a = in.next();
String b = in.next();
if(!map.containsKey(a)){
map.put(b,a);
}else{
map.put(b, map.get(a));
map.remove(a);
}
}
out.println(map.size());
for(Map.Entry<String, String> entry : map.entrySet())
out.println(entry.getValue()+ " "+entry.getKey());
}
private String get( HashMap<String, String> map, String a){
String S="";
for (Map.Entry<String, String> entry : map.entrySet()){
if (entry.getValue().equals(a)){
S=entry.getKey();
break;
}
}
return S;
}
}
public int factorial(int n) {
int fact = 1;
int i = 1;
while(i <= n) {
fact *= i;
i++;
}
return fact;
}
public static int BinarySearch(long temp,long[] sum,int r)
{
int l=0;
while(l<=r)
{
int mid=l+(r-l)/2;
if(sum[mid]==temp&&sum[mid]!=-1)
{
return mid;
}
if(sum[mid]>temp&&sum[mid]!=-1)
r=mid-1;
if(sum[mid]<temp&&sum[mid]!=-1)
l=mid+1;
}
return -1;
}
public static long gcd(long x,long y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int abs(int a,int b)
{
return (int)Math.abs(a-b);
}
public static long abs(long a,long b)
{
return (long)Math.abs(a-b);
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b)
{
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b)
{
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static long sort(int a[]){
int n=a.length;
int b[]=new int[n];
return mergeSort(a,b,0,n-1);
}
static long mergeSort(int a[],int b[],long left,long right){
long c=0;
if(left<right){
long mid=left+(right-left)/2;
c= mergeSort(a,b,left,mid);
c+=mergeSort(a,b,mid+1,right);
c+=merge(a,b,left,mid+1,right);
}
return c;
}
static long merge(int a[],int b[],long left,long mid,long right){
long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right){
if(a[i]<=a[j]){
b[k++]=a[i++];
}
else{
b[k++]=a[j++];c+=mid-i;
}
}
while (i <= (int)mid - 1)
b[k++] = a[i++];
while (j <= (int)right)
b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
a[i] = b[i];
return c;
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
cd39e0a2b5089871edd2445a17bca71e
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.HashMap;
import java.util.Set;
import java.util.Scanner;
public class Practice
{
public static void main(String args[])
{
int q,ans=0;
HashMap<String,String> map = new HashMap<>();
String str1,str2;
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
q=sc.nextInt();
ans=0;
while(q>0)
{
str1=sc.next();
str2=sc.next();
if(!map.containsValue(str1)){
map.put(str1, str2);
ans++;
}
else{
Set<String> set= map.keySet();
for(String key:set){
if(map.get(key).equals(str1)){
map.remove(key, str1);
map.put(key,str2);
break;
}
}
}
q--;
}
System.out.println(ans);
Set<String> set =map.keySet();
for(String key:set){
System.out.println(key+" "+map.get(key));
}
map.clear();
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
9ede571d676a05b14ed85b7db40fae69
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Random {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int temp=n;
Map<String,String> m=new HashMap<>();
while(temp>0){
m.put(sc.next(),sc.next());
temp--;
}
//System.out.println(m);
Set<String> set=m.keySet();
Map<String,String> m1=new HashMap<>();
for(String s:set){
String x = m.get(s);
while(true) {
if (m.containsKey(x)) {
x = m.get(x);
}
else if(m.containsValue(s)){
s=m.getOrDefault(x,"");
}
else
break;
}
if(s!="")
m1.put(s,x);
}
System.out.println(m1.size());
Set<String> set1=m1.keySet();
for(String s:set1){
System.out.print(s+" "+m1.get(s));
System.out.println();
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
a0f24f141fbcdbfd75b13d3a1526236f
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Random {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int temp=n;
Map<String,String> m=new HashMap<>();
while(temp>0){
m.put(sc.next(),sc.next());
temp--;
}
//System.out.println(m);
Set<String> set=m.keySet();
Map<String,String> m1=new HashMap<>();
for(String s:set){
String x = m.get(s);
while(true) {
if (m.containsKey(x)) {
x = m.get(x);
}
else if(m.containsValue(s)){
s="";
}
else
break;
}
if(s!="")
m1.put(s,x);
}
System.out.println(m1.size());
Set<String> set1=m1.keySet();
for(String s:set1){
System.out.print(s+" "+m1.get(s));
System.out.println();
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
906d5375b2e2ce976131bad7dde7587a
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> graph = new HashMap<>();
List<String> origins = new LinkedList<>();
int q = Integer.parseInt(reader.readLine());
for (int i = 0; i < q; ++i) {
StringTokenizer st = new StringTokenizer(reader.readLine());
String first = st.nextToken();
String second = st.nextToken();
if (!graph.containsKey(first)) {
origins.add(first);
}
graph.put(first, second);
graph.put(second, "");
}
reader.close();
System.out.println(origins.size());
for (String origin: origins) {
System.out.println(origin + " " + getLastName(graph, origin));
}
}
private static String getLastName(Map<String, String> graph, String name) {
while(graph.containsKey(name)) {
String tmp = graph.get(name);
if (tmp.length() == 0)
break;
name = tmp;
}
return name;
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
706c48ee4f9016c5421e43ec218f70d9
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
public class MishaChangingHandles {
public static void main(String[] args) {
Map<String, String> edges = new HashMap();
Set<String> children = new HashSet();
Map<String, String> results = new HashMap();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String a, b;
for (int i = 0; i < n; i++) {
a = sc.next();
b = sc.next();
edges.put(a, b);
children.add(b);
}
for (Map.Entry<String,String> entry : edges.entrySet()) {
String currentKey = entry.getKey();
if (children.contains(currentKey)) {
continue;
}
while (edges.containsKey(currentKey)) {
currentKey = edges.get(currentKey);
/* if (tempKey != null)
currentKey = tempKey;
else {
currentKey = entry.getValue();
break;
}
*/ }
results.put(entry.getKey(), currentKey);
}
System.out.println(results.size());
for (Map.Entry<String,String> entry : results.entrySet())
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
83165317ec611fa102dcb2192894d826
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class MishaandChangingHandles {
/**
* @param args
*/
static HashMap<String, String> handles = new HashMap<String, String>();
static HashSet<String> allhandles = new HashSet<String>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0 ; i < n ; i++) {
String temp1 = st.nextToken();
String temp2 = st.nextToken();
handles.put(temp1, temp2);
st = i == (n - 1)? null : new StringTokenizer(br.readLine());
allhandles.add(temp1);
allhandles.add(temp2);
}
ArrayList<String> handle = new ArrayList<String>();
for (String s : allhandles) {
handle.add(s);
}
int count = 0;
StringBuffer sb = new StringBuffer();
for (int i = 0 ; i < handle.size() ; i++) {
if(handles.containsKey(handle.get(i))) {
if (handles.containsKey(handle.get(i)) && handles.containsValue(handle.get(i)))
continue;
if(handles.containsKey(handles.get(handle.get(i)))) {
String temp = handles.get(handle.get(i));
while(true) {
if (!handles.containsKey(temp)) {
sb.append(handle.get(i) + " " + temp + '\n');
count++;
break;
}
String temp1 = handles.get(temp);
handles.remove(temp);
temp = temp1;
}
}
else {
if(!handles.containsKey(handles.get(handle.get(i))) && !handles.containsValue(handle.get(i))) {
sb.append(handle.get(i) + " " + handles.get(handle.get(i)) + '\n');
count++;
}
}
}
}
System.out.println(count);
System.out.print(sb);
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
306afa4735da729323bec0642439e176
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class codeforces
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList <String> al=new ArrayList<>();
String arr[][]=new String[n][2];
int counter=0;
for(int j = 0 ;j<n;j++)
{
String s1=sc.next();
String s2=sc.next();
al.add(s1);
al.add(s2);
int flag=0;
for(int i = 0 ;i<counter;i++)
{
if(s1.equals(arr[i][1]))
{
flag=1;
arr[i][1]=s2;
break;
}
}
for(int i = 0 ;i<counter;i++)
{
if(s2.equals(arr[i][1])||s2.equals(arr[i][0]))
{
flag=2;
break;
}
}
if(flag==2)
continue;
if(flag==0)
{
arr[counter][0]=s1;
arr[counter++][1]=s2;
}
}
System.out.println(counter);
for(int i = 0 ;i<counter;i++)
System.out.println(arr[i][0]+" "+arr[i][1]);
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
713239953520b977bffc38a401c645e8
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.nio.charset.StandardCharsets;
// import java.math.BigInteger;
// remember to check if n=0, n=1 are special cases
public class B {
static Writer wr;
public static void main(String[] args) throws Exception {
// long startTime = System.nanoTime();
// String testString = "";
// InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));
// Reader in = new Reader(stream);
Reader in = new Reader();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
wr = new Writer();
/* Precomputation */
// long elapsedTime = System.nanoTime() - startTime;
// double seconds = (double)elapsedTime / 1000000000.0;
// wr.writeRedLn(seconds);
/* Input */
int N = in.nextInt();
// in.readLine();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
ArrayList<String> rev_map = new ArrayList<>();
int idx = 0;
while(N-->0) {
String line = in.readLine().trim();
if(line.length()==0) {
N++;
continue;
}
String[] s = line.split(" ");
int a = idx;
if(map.get(s[0])!=null) {
a = map.get(s[0]);
}
else {
adj.add(new ArrayList<>());
map.put(s[0],a);
rev_map.add(s[0]);
idx++;
}
int b = idx++;
map.put(s[1], b);
rev_map.add(s[1]);
adj.add(new ArrayList<>());
adj.get(a).add(b);
// adj.get(b).add(a);
}
boolean[] visited = new boolean[rev_map.size()];
int ans_count = 0;
StringBuilder sb = new StringBuilder();
for(int i=0;i<rev_map.size();i++) {
if(visited[i]) continue;
Stack<Integer> st = new Stack<>();
st.add(i);
visited[i] = true;
int last = 0;
while(st.size()>0) {
int curr = st.pop();
for(Integer x : adj.get(curr)) {
if(visited[x]) continue;
st.add(x);
visited[x] = true;
}
last = curr;
}
ans_count++;
sb.append(rev_map.get(i) + " " + rev_map.get(last) + "\n");
}
out.write(ans_count + "\n");
out.write(sb.toString());
// out.write("\n");
out.flush();
}
}
class Writer {
public void writeRedLn(Object x) { writeRedLn(x+""); }
public void writeBlueLn(Object x) { writeBlueLn(x+""); }
public void writeGreenLn(Object x) { writeGreenLn(x+""); }
public void writePinkLn(Object x) { writePinkLn(x+""); }
public void writeRedLn(String x) { System.out.println((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); }
public void writeBlueLn(String x) { System.out.println((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
public void writeGreenLn(String x) { System.out.println((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
public void writePinkLn(String x) { System.out.println((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); }
public void writeRed(String x) { System.out.print((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); }
public void writeBlue(String x) { System.out.print((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
public void writeGreen(String x) { System.out.print((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
public void writePink(String x) { System.out.print((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); }
}
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(InputStream stream){din=new DataInputStream(stream);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;}
public String readLine()throws IOException{byte[] buf=new byte[1024];int cnt=0,c;
while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);}
public char nextChar()throws IOException{byte c=read();while(c<=' ')c=read();return (char)c;}
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\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
d5c1db2113ec644b702e8468e0bedac8
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.HashMap;
import java.util.Scanner;
public class CF501B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashMap<String, User> map = new HashMap<>();
while(n-->0) {
String oldName = sc.next();
String newName = sc.next();
if(!map.containsKey(oldName)) map.put(newName, new User(oldName, newName));
else {
User u = map.get(oldName);
u.curName = newName;
map.remove(oldName);
map.put(newName, u);
}
}
System.out.println(map.size());
for(User u: map.values()) System.out.println(u);
}
static class User {
String originalName;
String curName;
public User (String oN, String cN) {
originalName = oN;
curName = cN;
}
public String toString() {
return originalName+" "+curName;
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
fba536ce6ab56c94e35c1d2b04412841
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static Graph g;
static int n ;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
Hashtable<String,Integer> h = new Hashtable<>();
int q=1;
n = in.nextInt();
String[] names = new String[2*n+1];
g = new Graph(2*n+2);
boolean[] check = new boolean[2*n+1];
for (int i=0;i<2*n+1;i++) {
check[i] = true;
names[i] = "-";
}
int cntr=0;
for (int i =0;i<n;i++)
{
String s1 = in.readString();
String s2 = in.readString();
if (!h.containsKey(s1))
{
h.put(s1,q);
q++;
names[q-1]=s1;
cntr++;
}
if (!h.containsKey(s2))
{
h.put(s2,q);
q++;
names[q-1]=s2;
}
check[h.get(s2)]=false;
addEdge(h.get(s1),h.get(s2));
}
out.printLine(cntr);
for (int i =1;i<2*n+1;i++)
{
if (check[i]&&!names[i].equals("-"))
{
out.print(names[(i)]+" "+names[DFS(i)]);
out.printLine();
}
}
out.flush();
}
static int DFS(int v)
{
boolean[] visited = new boolean[g.n];
return DFSUtil(visited,v);
}
static int DFSUtil(boolean[] visited,int v)
{
visited[v] = true;
int i=0;
if (g.adjList[v].size()==0)
return v;
else {
while (i < g.adjList[v].size()) {
if (!visited[g.adjList[v].get(i)])
return DFSUtil(visited, g.adjList[v].get(i));
i++;
}
}
return -1;
}
static void addEdge(int i ,int j)
{
g.adjList[i].addFirst(j);
}
}
class Graph {
int n;
LinkedList<Integer>[] adjList;
public Graph(int n) {
this.n = n;
adjList = new LinkedList[n];
for (int i = 0; i < n; i++)
adjList[i] = new LinkedList<>();
}
}
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;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
ee19618ace020e9b5133952c0f5452dc
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
public class solution{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
String[][] handles=new String[1000][2];
int tc=in.nextInt();
handles[0][0]=in.next();
handles[0][1]=in.next();
int ind=1;
for(int i=1;i<tc;++i){
String old=in.next();
String news=in.next();
int temp=0;
for(int j=0;j<ind;++j){
if(old.equals(handles[j][1])){
handles[j][1]=news;
++temp;
}
}
if(temp==0){
handles[ind][0]=old;
handles[ind][1]=news;
++ind;
}
}
System.out.println(""+ind);
for(int i=0;i<ind;++i){
System.out.println(handles[i][0]+" "+handles[i][1]);
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
402c4542401718cc18b9cb4f99680740
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
//package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Solve solve = new Solve(new Scanner(System.in));
solve.start();
}
private static class Solve {
private final Scanner SCANNER;
private String []names;
private HashMap<String , Integer> hashMap;
private int sz ;
private int []parent;
private List<Integer> arrayList;
public Solve(Scanner scanner) {
this.SCANNER = scanner;
hashMap = new HashMap<>();
arrayList = new ArrayList<>();
names = new String[2009];
parent = new int[2009];
sz = 1;
}
public void start(){
int n = SCANNER.nextInt();
initParents();
String u , v;
for(int i = 0 ; i < n ; ++i){
u = SCANNER.next();
v = SCANNER.next();
if(u.equals(v)){
continue;
}
if(!hashMap.containsKey(u)){
hashMap.put(u , sz);
names[sz] = u;
sz++;
}
if(!hashMap.containsKey(v)){
hashMap.put(v , sz);
names[sz] = v;
arrayList.add(sz);
sz++;
}
int uu = hashMap.get(u);
int vv = hashMap.get(v);
if(arrayList.contains(uu)){
arrayList.remove(arrayList.indexOf(uu));
}
parent[vv] = findParent(uu);
}
ArrayList<String> answers = new ArrayList<>();
for(int i : arrayList){
answers.add(names[findParent(i)] + " " + names[i]);
}
answers.sort(String::compareTo);
System.out.println("" + answers.size());
for(String answer : answers){
System.out.println(answer);
}
}
private void initParents() {
for(int i = 0 ; i < parent.length ; ++i){
parent[i] = i;
}
}
private int findParent(int node){
if(parent[node] == node){
return node;
}else{
return findParent(parent[node]);
}
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
a480b5be6ad067821aced9d747624f89
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
private static final Boolean FILE_IO_ENABLE = false;
private static final Integer BUFFER_SIZE = 1 << 12;
private static final String INPUT_FILE_NAME = "input.txt";
private static final String OUTPUT_FILE_NAME = "output.txt";
private static PrintWriter output;
private static Scanner input;
private static void init() throws Exception {
if (FILE_IO_ENABLE) {
output = new PrintWriter(new BufferedWriter(new FileWriter(new File(OUTPUT_FILE_NAME)), BUFFER_SIZE));
input = new Scanner(new BufferedInputStream(new FileInputStream(new File(INPUT_FILE_NAME)), BUFFER_SIZE));
} else {
output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out), BUFFER_SIZE));
input = new Scanner(new BufferedInputStream(System.in, BUFFER_SIZE));
}
}
private static void exit() throws Exception {
output.flush();
System.exit(0);
}
public static void main(String[] args) throws Exception {
init();
Map<String, String> oldNewHandles = new HashMap<>();
Map<String, String> newOldHandles = new HashMap<>();
Integer queryNumber = input.nextInt();
input.nextLine();
for (Integer i = 0; i < queryNumber; ++i) {
String previousHandle = input.next();
String nextHandle = input.next();
if (!newOldHandles.containsKey(previousHandle)) {
oldNewHandles.put(previousHandle, nextHandle);
newOldHandles.put(nextHandle, previousHandle);
continue;
}
String oldHandle = newOldHandles.get(previousHandle);
oldNewHandles.put(oldHandle, nextHandle);
newOldHandles.put(nextHandle, oldHandle);
}
output.println(oldNewHandles.size());
for (Map.Entry<String, String> oldNewHandle : oldNewHandles.entrySet()) {
output.println(oldNewHandle.getKey() + " " + oldNewHandle.getValue());
}
exit();
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
f6ec511a2e1a8c353071de7a64a77edf
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class B {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
HashMap<String,String> map = new HashMap<>();
HashSet<String> left = new HashSet<>();
HashSet<String> right = new HashSet<>();
while(n-->0){
String oldHandle = ns(), newHandle = ns();
map.put(oldHandle, newHandle);
left.add(oldHandle);
right.add(newHandle);
}
HashSet<String> done = new HashSet<>();
for(String key: map.keySet()){
if(right.contains(key)) continue;
String ans = map.get(key);
while(map.get(ans)!=null){
ans = map.get(ans);
}
done.add(key + " " + ans);
// out.println(key + " " + ans);
}
out.println(done.size());
for(String str: done) out.println(str);
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new B().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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
1aab5d797428b765097a3e00213bec2d
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// write your code here
int n = Integer.parseInt(br.readLine());
HashSet<String> hash = new HashSet<>();
HashMap<String,String> map = new HashMap<>();
int [] arr = new int[n*n];
while (n-->0){
StringTokenizer st = new StringTokenizer(br.readLine());
String u = st.nextToken();
String v = st.nextToken();
if (!map.containsKey(u)){
if (!map.containsValue(u)){
hash.add(u);
}
map.put(u,v);
}
}
pw.println(hash.size());
for (String u:hash){
pw.print(u);
String v = u;
while (map.containsKey(v)){
v = map.get(v);
}
pw.print(" "+v+"\n");
}
pw.flush();
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
1b5285b424e0aa24bbaead923e8391ca
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.io.*;//1 1 2 3 3 2 2 4 8 8
public class r{
public static void main(String[] args)throws IOException{
File f=new File("/home/ujjwal/Desktop/new.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
Scanner sc=new Scanner(System.in);long sum=0;
//StringTokenizer st=new StringTokenizer(br.readLine());
int q=sc.nextInt();/**5
Misha MikeMirzayanov
Vasya VasyaPetrov123
Petrov VasyaPetrov123
0 0
Petya Ivanov
**/
ArrayList<String> a1=new ArrayList<String>();ArrayList<String> a2=new ArrayList<String>();//3
for(int i=0;i<q;i++){
a1.add(sc.next());
a2.add(sc.next());
}
for(int i=0,k=0;i<q-1;i++,k++){
for(int j=i+1;j<q;j++){
if(a2.get(i).equals(a1.get(j)) && !a2.get(i).equals("@#") && !a1.get(j).equals("@#") ){
a2.set(i,a2.get(j));
a1.set(j,"@#");
a2.set(j,"@#");
i--;
break;
}
}
}
for(int i=0;i<a1.size();i++){
if(a1.get(i).contentEquals("@#") && a2.get(i).contentEquals("@#")){
a1.remove(i);a2.remove(i);i--;
}
}System.out.println(a1.size());
for(int i=0;i<a1.size();i++){
System.out.println(a1.get(i)+" "+a2.get(i));
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
465dd3d74bca41bcf778d3f96bfcc468
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
String old[]=new String[(int)t];
String nw[]=new String[(int)t];
for (int i=0;i<t ;i++ )
{
String k[]=br.readLine().split(" ");
old[i]=k[0];
nw[i]=k[1];
}
HashMap<String,String> map=new HashMap<String,String>();
for(int i=0;i<t;i++)
{
int c=0;
for (int j=0;j<t ;j++ )
{
if(nw[i].equals(old[j]) && nw[i]!="" && old[j]!="" )
{
nw[i]=nw[j];
old[j]="";
nw[j]="";
}/*else
{
if(c==t)
{
boolean p=false;
for (int k=0;k<t ;k++ )
{
if((old[i]).equals(nw[k]))
{
p=true;
break;
}
}
if(p==false)
map.put(old[i],nw[i]);
}
}*/
}
}
int c=0;
for(int i=0;i<t;i++)
{
if(old[i]!="" && nw[i]!="")
c++;
}
System.out.println(c);
for(int i=0;i<t;i++)
{
if(old[i]!="" && nw[i]!="")
System.out.println(old[i]+" "+nw[i]);
}
/*for (Map.Entry mapElement : map.entrySet()) {
System.out.println(mapElement.getKey() + " " + mapElement.getValue());
} */
} catch(Exception e) {
return;}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
a3a8e46aba4d9f7ec6c40b099dcf3585
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Vector;
import com.sun.javafx.collections.MappingChange.Map;
public class hazem {
static int [] p = {1,2,3,4,5} ;
public static void main(String[] args) throws IOException{
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n =sc.nextInt();
String arr[][]= new String[n][2];
for(int i=0 ;i<n;i++){
String x =sc.nextToken();
String y =sc.nextToken();
boolean yes =false;;
for(int j =0;j<arr.length;j++){
if(x.equals(arr[j][1])){
arr[j][1]=y ;
yes=true;
}
}
if(yes==false)
{
arr[i][0]=x ;
arr[i][1]=y;
}
}
int c =0;
for(int i =0;i<arr.length ;i++)
if(arr[i][0]==null)
;
else{
c++;
//out.println(arr[i][0]+" "+arr[i][1]);
}
out.println(c);
for(int i =0;i<arr.length ;i++)
if(arr[i][0]==null)
;
else{
out.println(arr[i][0]+" "+arr[i][1]);
}
out.close();
}
static boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
5ae12ad746088cb970514f26355b1620
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
/*
by Fuzious
7/5/2019
*/
import java.io.*;
import java.util.*;
public class codeforces {
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
int N=sc.nextInt();
Map<String,Integer> HM=new HashMap<>();
String q[]=new String[2*N];
for (int n = 0; n < q.length;) {
String str=sc.readString();
HM.put(str,HM.size());
q[n++]=str;
str=sc.readString();
HM.put(str,HM.size());
q[n++]=str;
}
Map<String,Integer> HM2=new HashMap<>(HM);
// System.out.println(HM+" "+HM2);
DisSet DS=new DisSet(HM.size());
for (int n = 0; n < q.length;) {
String a=q[n++];
String b=q[n++];
DS.weightedunion(HM.get(a),HM.get(b));
HM2.put(a,-1);
}
String outp="";
int c=0;
for (Map.Entry<String,Integer> entry : HM2.entrySet()) {
if(entry.getValue()!=-1) {
++c;
int root=DS.root(entry.getValue());
String rootString=getKeyByValue(HM,root);
outp+=(rootString+" "+entry.getKey()+"\n");
}
}
out.println(c);
out.println(outp);
out.close();
}
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static int mod = 1000000000 + 7;
static class DisSet{
int Arr[],size[];
DisSet(int n){
Arr=new int[n];
size=new int[n];
for (int i = 0; i < n; i++) {
Arr[i]=i;
size[i]=1;
}
}
int root(int i)
{
while(Arr[ i ] != i)
{
Arr[ i ] = Arr[ Arr[ i ] ] ;
i = Arr[ i ];
}
return i;
}
int setSize(int x){
return size[root(x)];
}
void weightedunion(int A,int B){
int root_A = root(A);
int root_B = root(B);
if(root_A==root_B)
return;
if(size[root_A] < size[root_B ])
{
Arr[ root_A ] = Arr[root_B];
size[root_B] += size[root_A];
}
else
{
Arr[ root_B ] = Arr[root_A];
size[root_A] += size[root_B];
}
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public double nextDouble() {
return (Double.parseDouble(readString()));
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 8
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
455628c5e154ba43bd7e7434e6e2bb33
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
public class C501 {
public static void main(String[] args){
Scanner z = new Scanner (System.in);
final int maxn = 1005;
boolean ok;
String s[]= new String[maxn], t[] = new String[maxn], a, b, c;
String item[] = new String[4];
int q=z.nextInt(), n=0, x=0;c=z.nextLine();
for (int i=0;i<q;i++) {s[i]="";t[i]="";}
for (int i=0;i<q;i++){
c=z.nextLine();//System.out.println(c);
item[0]="";item[1]="";x=0;
for (int j=0;j<c.length();j++)
if (c.charAt(j)==' ')x++;
else item[x]+=c.charAt(j);
a=item[0];b=item[1];//System.out.println(a+" "+b);
ok=false;
for (int j=0;j<n;j++) if (a.equals(t[j])) {ok=true;t[j]=b;break;}
if (!ok) {n++;s[n-1]=a;t[n-1]=b;}
}
System.out.println(n);
for (int i=0;i<n;i++) System.out.println(s[i]+" "+t[i]);
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
5565092432579c04c88d15254c6904a5
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Set;
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 TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int q = in.nextInt();
String oldHandle,newHandle;
HashMap<String,String> res = new HashMap<String, String>();
HashMap<String,String> cur = new HashMap<String, String>();
for (int i = 0; i < q; i++) {
oldHandle = in.next();
newHandle = in.next();
if(!cur.containsKey(oldHandle)){
res.put(oldHandle,newHandle);
cur.put(newHandle,oldHandle);
} else {
String oriHandle = cur.get(oldHandle);
res.put(oriHandle,newHandle);
cur.put(newHandle,oriHandle);
}
}
out.println(res.size());
for(String key : res.keySet()){
out.printf("%s %s\n",key,res.get(key));
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
c2467920641ef80da5e29d0f8f48dfd3
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class MainB {
MyScanner sc = new MyScanner();
Scanner sc2 = new Scanner(System.in);
final int MOD = 1000000007;
int[] dx = { 1, 0, 0, -1 };
int[] dy = { 0, 1, -1, 0 };
void run() {
int q = sc.nextInt();
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, String> ans = new HashMap<String, String>();
HashSet<String> used = new HashSet<String>();
String[] chrono = new String[q];
for (int i = 0; i < q; i++) {
String old = sc.next();
String renew = sc.next();
map.put(old, renew);
chrono[i] = old;
}
for (int i = 0; i < q; i++) {
String old = chrono[i];
String res = chrono[i];
String next = "";
if (used.contains(old)) {
continue;
}
used.add(old);
boolean find = false;
while (!find) {
if (!map.containsKey(old)) {
next = old;
find = true;
} else {
old = map.get(old);
used.add(old);
}
}
ans.put(res, next);
}
System.out.println(ans.size());
for (String key : ans.keySet()) {
System.out.println(key + " " + ans.get(key));
}
}
public static void main(String[] args) {
new MainB().run();
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void debug2(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
boolean inner(int h, int w, int limH, int limW) {
return 0 <= h && h < limH && 0 <= w && w < limW;
}
void swap(int[] x, int a, int b) {
int tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
// find minimum i (a[i] >= border)
int lower_bound(int a[], int border) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (border <= a[mid]) {
r = mid;
} else {
l = mid;
}
}
// r = l + 1
return r;
}
class MyScanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-')
return -nextInt();
int res = 0;
do {
res *= 10;
res += c - '0';
c = System.in.read();
} while ('0' <= c && c <= '9');
return res;
} catch (Exception e) {
return -1;
}
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String next() {
try {
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while (Character.isWhitespace(c))
c = System.in.read();
do {
res.append((char) c);
} while (!Character.isWhitespace(c = System.in.read()));
return res.toString();
} catch (Exception e) {
return null;
}
}
int[] nextIntArray(int n) {
int[] in = new int[n];
for (int i = 0; i < n; i++) {
in[i] = nextInt();
}
return in;
}
int[][] nextInt2dArray(int n, int m) {
int[][] in = new int[n][m];
for (int i = 0; i < n; i++) {
in[i] = nextIntArray(m);
}
return in;
}
double[] nextDoubleArray(int n) {
double[] in = new double[n];
for (int i = 0; i < n; i++) {
in[i] = nextDouble();
}
return in;
}
long[] nextLongArray(int n) {
long[] in = new long[n];
for (int i = 0; i < n; i++) {
in[i] = nextLong();
}
return in;
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
5acb1d7f8ce16877f9d93bfd319c6e0e
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
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.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
//################################################################################################################
public class R285D2B {
public static void main(String[] args) {
R285D2B b = new R285D2B();
InputReader1 reader = b.new InputReader1(System.in);
OutputWriter writer = b.new OutputWriter(System.out);
// think about the brute-force approach
// read input
// code boundary conditions
int n = reader.readInt();
Map<String, String> cmap = new HashMap<String, String>();
Map<String, String> pmap = new HashMap<String, String>();
Map<String, String> answer = new HashMap<String, String>();
for (int i = 0; i < n; i++) {
String line = reader.readLine();
String[] words = line.split(" ");
cmap.put(words[0], words[1]);
pmap.put(words[1], words[0]);
}
for (String pa : cmap.keySet()) {
String c = cmap.get(pa);
if (!cmap.containsKey(c)) {
String tmp = c;
while (pmap.containsKey(tmp)) {
tmp = pmap.get(tmp);
}
answer.put(tmp, c);
}
}
writer.println(answer.size());
StringBuilder sbd = new StringBuilder();
for (String key : answer.keySet()) {
sbd.append(key);
sbd.append(" ");
sbd.append(answer.get(key));
sbd.append("\n");
}
writer.println(sbd.toString());
reader.close();
writer.close();
}
class InputReader1 {
// private final boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader1(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int length = readInt();
if (length < 0)
return null;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
bytes[i] = (byte) read();
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
return new String(bytes);
}
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public boolean readBoolean() {
return readInt() == 1;
}
public void close() {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(String s) {
writer.println(s);
}
public void println(int x) {
writer.println(x);
}
public void print(int x) {
writer.print(x);
}
public void println(long x) {
writer.println(x);
}
public void printSpace() {
writer.print(" ");
}
public void close() {
writer.close();
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
11411e0ecdf83db8c8d44fd99f03ce45
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int q = Integer.parseInt(in.readLine());
HashMap<String, String> mapOrig = new HashMap<String, String>();
HashMap<String, String> mapToOrig = new HashMap<String, String>();
String[] t;
for (int i=0;i<q;i++) {
t = in.readLine().split(" ");
String name = t[0];
String newName = t[1];
String s = mapToOrig.get(name);
if (s==null) {
mapOrig.put(name, newName);
mapToOrig.put(newName, name);
} else {
mapOrig.remove(s);
mapOrig.put(s, newName);
mapToOrig.remove(name);
mapToOrig.put(newName, s);
}
}
out.println(mapOrig.size());
for (String name : mapOrig.keySet()) {
out.println(name +" "+mapOrig.get(name));
}
out.close();
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
ba2c8e6678f51cd8cb978e83b95bfb63
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.*;
public class per
{
public static void main(String []args)
{
Scanner s=new Scanner(System.in);
int n=Integer.parseInt(s.nextLine());
String a[]=new String[n];
String b[]=new String[n];
for(int i=0;i<n;i++)
{
String c[]=new String[2];
String h=s.nextLine();
c=h.split(" ");
a[i]=c[0];
b[i]=c[1];
//System.out.println(a[i]+" "+b[i]);
}
String c[][]=new String[n][2];
int co=0;
for(int i=0;i<n;i++)
{
String k=a[i];
String l=b[i];
int flag=0;
for(int j=0;j<co;j++)
{
if(c[j][1].equals(k))
{
//System.out.println(" "+l+" "+j);
c[j][1]=l;
flag=1;
}
}
if(flag==0)
{
//System.out.println(co+" " +k+" "+l);
c[co][0]=k;
c[co][1]=l;
co++;
}
}
System.out.println(co);
for(int i=0;i<co;i++)
{
System.out.println(c[i][0]+" " +c[i][1]);
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
f26f976ce809b00a390eefd0dc31fca5
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class B {
void run(){
Scanner sc = new Scanner(System.in);
int Q = sc.nextInt();
Map<String, String> res = new HashMap<String, String>();
while(Q--!=0){
String old = sc.next(), newh = sc.next();
boolean f = false;
for(String key:res.keySet()){
if(old.equals(res.get(key))){
res.put(key, newh);
f = true;
break;
}
}
if(!f) res.put(old, newh);
}
System.out.println(res.size());
for(String old: res.keySet()){
System.out.println(old+" "+res.get(old));
}
}
void debug(Object...o){
System.out.println(Arrays.deepToString(o));
}
public static void main(String[] args) {
new B().run();
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
ca7435e589969e863a7abb0390d1e2d2
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
//package Contest_Div285;
//Xudo xoxlasa Accepted;
import java.util.Scanner;
import java.util.TreeMap;
public class B {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
TreeMap<String, String>mp1=new TreeMap<String, String>();
TreeMap<String, String>mp2=new TreeMap<String, String>();
String s1="",s2="";
for (int i =1; i <=n; i++) {
s1=sc.next();
s2=sc.next();
if(mp2.containsKey(s1)){
mp1.put(mp2.get(s1), s2);
mp2.put(s2, mp2.get(s1));
}else{
mp1.put(s1, s2);
mp2.put(s2, s1);
}
}
System.out.println(mp1.size());
for(String s:mp1.keySet()){
System.out.println(s+" "+mp1.get(s));
}
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
d0aed512d31f1c6347e2ba6b686b81ee
|
train_001.jsonl
|
1421053200
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
256 megabytes
|
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner obj=new Scanner(System.in);
int q=obj.nextInt();
String arr[]=new String[q+1];String brr[]=new String[q+1];
for(int i=0;i<=q;i++){ arr[i]=obj.nextLine(); }
int o=0,c=0;String e="";String z="";
boolean w[]=new boolean[q+1];Arrays.fill(w,true);
for(int i=1;i<=q;i++)
{
if(w[i])
{ o=0;
int p=arr[i].indexOf(' ',0);//System.out.println("p="+p);
String m=arr[i].substring(p+1);e=arr[i].substring(0,p);//System.out.println("m="+m);
for(int j=i+1;j<=q;j++)
{
int r=arr[j].indexOf(' ',0);
String n=arr[j].substring(0,r);//System.out.println("n="+n);
//System.out.println("z="+z);
if(n.equals(m)){ o=1;z=arr[j].substring(r+1);m=z;w[j]=false; }
}
if(o==0){ brr[c]=arr[i];c++; }
else{brr[c]=e+" "+z;c++;}
}
} System.out.println(c);
for(int i=0;i<c;i++){ System.out.println(brr[i]); }
}
}
|
Java
|
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
|
1 second
|
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
| null |
Java 6
|
standard input
|
[
"data structures",
"dsu",
"strings"
] |
bdd98d17ff0d804d88d662cba6a61e8f
|
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
| 1,100 |
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
|
standard output
| |
PASSED
|
97e9252e6788fcd133d08cafe2c4db0d
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main{
static long m=998244353l; //line 156 modInverse
static boolean[] vis; //line 74 and 91 hasElement ans pth_fnd
public static void main(String[] args) throws IOException{
// long sttm=System.currentTimeMillis();
int MAX=1000000007;
FastReader sc=new FastReader();
OutputStream out=new BufferedOutputStream(System.out);
int t=sc.nextInt();
while(t-->0){
int[][] sdk=new int[9][9];
for(int i=0;i<9;i++){
String s=sc.next();
for(int j=0;j<9;j++){
sdk[i][j]=s.charAt(j)-'0';
}
}
sdk[0][0]=(sdk[0][0]%9)+1;
sdk[3][1]=(sdk[3][1]%9)+1;
sdk[6][2]=(sdk[6][2]%9)+1;
sdk[1][3]=(sdk[1][3]%9)+1;
sdk[4][4]=(sdk[4][4]%9)+1;
sdk[7][5]=(sdk[7][5]%9)+1;
sdk[2][6]=(sdk[2][6]%9)+1;
sdk[5][7]=(sdk[5][7]%9)+1;
sdk[8][8]=(sdk[8][8]%9)+1;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
out.write((sdk[i][j]+"").getBytes());
}
out.write('\n');
}
}
out.flush();
// long sttm=System.currentTimeMillis();
}
public static long cnt_sum_k_subar(long[] a,int n,int k){
HashMap<Long,Long> map=new HashMap<Long,Long>();
long ret=0;
long cur_sum=0;
for(int i=0;i<n;i++){
cur_sum+=a[i];
if(cur_sum==k){
ret++;
}
if(map.containsKey(cur_sum-k)){
ret+=map.get(cur_sum-k);
}
if(map.containsKey(cur_sum)){
map.put(cur_sum, map.get(cur_sum)+1);
}
else{
map.put(cur_sum, (long)1);
}
}
return ret;
}
public static ArrayList<Integer> lcm(int num){
ArrayList<Integer> arrl=new ArrayList<Integer>();
while(num%2==0){
arrl.add(2);
num/=2;
}
for(int i=3;i*i<=num;i+=2){
while(num%i==0){
arrl.add(i);
num/=i;
}
}
if(num>2){
arrl.add(num);
}
return arrl;
}
static long modInverse(long a,long m)
{
long m0 = m;
long y = 0l, x = 1l;
if (m == 1)
return 0l;
while (a > 1)
{
long q = a / m;
long t = m;
m = a % m;
a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0)
x += m0;
return x;
}
public static TreeSet<Long> arr_fact(long num){
TreeSet<Long> arr=new TreeSet<Long>();
int cnt=0;
for(long i=1;i*i<=num;i++){
if(num%i==0){
if(i*i==num){
cnt+=1;
arr.add(i);
}
else{
arr.add(i);arr.add(num/i);
cnt+=2;
}
}
}
return arr;
}
public static int num_fact(int num){
ArrayList<Integer> arr=new ArrayList<Integer>();
int cnt=0;
for(int i=1;i*i<=num;i++){
if(num%i==0){
if(i*i==num){
cnt+=1;
}
else{
cnt+=2;
}
}
}
return cnt;
}
public static long cal(int k,int x){
long val=1;
for(int i=0;i<k;i++){
val*=2;
if(val>x){
break;
}
}
return val;
}
public static void sort_inc(int[][] arr,int col){ //change dimention if req
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(final int[] entry1,final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
public static boolean prime(int n){
for(int i=2;i*i<=n;i++){
if(n%i==0){
return false;
}
}
return true;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
34685cd70405358193981f59a4cc2eaa
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Anti {
public static void main(String [] args) {
Scanner in = new Scanner (System.in);
int t = in.nextInt();
for(int cs = 1; cs <= t; cs++) {
char s[][] = new char [9][9];
for(int i = 0; i < 9; i++) {
s[i] = in.next().toCharArray();
}
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(s[i][j] == '1') s[i][j] = '2';
}
System.out.println(s[i]);
}
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
b551ca4eb5467db4cc91baa621524b05
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.Scanner;
public class antiSudoku {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
StringBuilder ans = new StringBuilder();
while (--T >= 0) {
StringBuilder matrix = new StringBuilder();
for (int i = 0; i < 9; i++)
matrix.append(sc.next());
for (int i = 0; i < 81; i++) {
if (matrix.charAt(i) == '1')
ans.append('2');
else
ans.append(matrix.charAt(i));
if ((i + 1) % 9 == 0)
ans.append('\n');
}
}
System.out.print(ans);
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
c48907f30133f7ee5a61e2f68b9f0ae7
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class AntiSudoku{
public static void main(String args[]){
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
int t=Integer.parseInt(br.readLine());
while(t-- >0){
int[][] s=new int[9][9];
String temp;
for (int i = 0; i < 9; i++) {
temp=br.readLine().trim();
for (int j = 0; j < 9; j++) {
s[i][j]=Integer.parseInt(temp.charAt(j)+"");
}
}
int k=0;
for (int i = 0; i < 9; i++) {
s[i][k+(i/3)]=s[i][k+(i/3)]%9+1;
k=(k+3)%9;
}
StringBuilder b=new StringBuilder();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
b.append(s[i][j]);
}
b.append("\n");
}
System.out.print(b);
}
br.close();
}
catch(IOException e){}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
703328eb8d1d69eef7d32e2914453540
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
public class Main{
public static void main(String []args){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
in.nextLine();
while(t>0)
{
String[] s = new String[9];
for(int i=0;i<9;i++)
{
s[i]=in.nextLine();
}
int cnt=0;
for(int i=0;i<9;i=i+3)
{
int cnt1=0;
for(int k=i,j=cnt;cnt1<3;k++,j=j+3,cnt1++)
{
if(s[k].charAt(j)=='1')
{
s[k]=s[k].substring(0,j)+"2"+s[k].substring(j+1,s[k].length());
}
else
{
s[k]=s[k].substring(0,j)+"1"+s[k].substring(j+1,s[k].length());
}
}
cnt++;
}
for(int i=0;i<9;i++)
{
System.out.println(s[i]);
}
t--;
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
ce84a7fa7e8e60774b79f2fabaae07a2
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
public class A {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[][] arr = new int[9][9];
StringBuffer out = new StringBuffer();
for (int t = Integer.parseInt(br.readLine()); t > 0; t--) {
for (int a = 0; a < 9; a++) {
char[] ch = br.readLine().toCharArray();
for (int b = 0; b < 9; b++)
arr[a][b] = ch[b] - '0';
}
arr[0][0] = arr[0][0] % 9 + 1;
arr[1][3] = arr[1][3] % 9 + 1;
arr[2][6] = arr[2][6] % 9 + 1;
arr[3][1] = arr[3][1] % 9 + 1;
arr[4][4] = arr[4][4] % 9 + 1;
arr[5][7] = arr[5][7] % 9 + 1;
arr[6][2] = arr[6][2] % 9 + 1;
arr[7][5] = arr[7][5] % 9 + 1;
arr[8][8] = arr[8][8] % 9 + 1;
for (int a = 0; a < 9; a++) {
for (int b = 0; b < 9; b++)
out.append(arr[a][b]);
out.append('\n');
}
}
System.out.print(out);
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
5e51544af4f6c36d71f9a3fbb5b786d7
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int t = nextInt();
for (int q = 0; q < t; q++) {
char[][] s = new char[9][9];
for (int i = 0; i < 9; i++) {
s[i] = next().toCharArray();
}
int[][] a = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
a[i][j] = s[i][j] - '0';
}
}
a[0][1] = a[0][0];
a[1][4] = a[1][3];
a[2][7] = a[2][6];
a[3][2] = a[3][1];
a[4][5] = a[4][4];
a[5][8] = a[5][7];
a[6][0] = a[6][2];
a[7][3] = a[7][5];
a[8][6] = a[8][8];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
pw.print(a[i][j]);
}
pw.println();
}
}
pw.close();
}
static ArrayList<Pair>[] g;
static PrintWriter pw;
static StringTokenizer st = new StringTokenizer("");
static BufferedReader br;
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class Pair {
int v;
int time;
public Pair(int v, int time) {
this.v = v;
this.time = time;
}
}
class Pair_Sort implements Comparator<Pair> {
public int compare(Pair o1, Pair o2) {
return Integer.compare(o1.time, o2.time);
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
765612737946a158abc3ecab9b250b97
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
public class Solution{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
StringBuffer sb = new StringBuffer();
while(t-->0){
int[][]arr=new int[9][9];
for(int i = 0;i<9;i++){
String s = sc.next();
for(int j = 0;j<9;j++){
int x = Integer.parseInt(s.charAt(j)+"");
if(x==1) x=3;
arr[i][j]=x;
}
}
for(int i = 0;i<9;i++){
for(int j = 0;j<9;j++){
sb.append(arr[i][j]);
}
sb.append("\n");
}
}
System.out.println(sb);
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
f571a2f647f70184b25a8e660b76d4b6
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.awt.datatransfer.FlavorEvent;
import java.io.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
public class Main {
private static void solver(InputReader sc, PrintWriter out) throws Exception {
int test = sc.nextInt();
for(int ii=0; ii<test; ii++) {
int arr[][] = new int[9][9];
for(int i=0;i<9;i++){
String s = sc.next();
for(int j=0;j<9;j++){
int x = (int)s.charAt(j)-48;
if(x==2)
x=1;
arr[i][j] = x;
}
}
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
out.print(arr[i][j]);
}
out.println();
}
}
}
/* private static boolean isprime(int x) {
if (x == 2)
return true;
int sqs = (int) Math.sqrt(x);
for (int i = 2; i <= sqs; i++) {
if (x % i == 0)
return false;
}
return true;
}
private static int gcd (int a, int b) {
if (b == 0)
return a;
else
return gcd (b, a % b);
}
private static long helper(long x){
long ans = (x * (x-1))/2;
return ans;
}*/
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver(in,out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n){
int arr[] = new int[n];
for(int i=0;i<n;i++) arr[i] = nextInt();
return arr;
}
}
}
class Pair {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
Pair pair = (Pair) o;
return this.x < pair.x && this.y==pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
cccb654ff4783e2c0cd2160327c9be28
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.lang.reflect.Array;
import java.util.*;
public class Main {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
new Main().run();
}
void run() {
int t = sc.nextInt();
for (int i=0; i<t; i++) {
StringBuilder sb = new StringBuilder();
String[] arr = new String[9];
for (int j=0; j<9; j++) {
arr[j] = sc.next();
}
// System.out.println(arr[0]);
for (int j=0; j<3; j++) {
String tmp = arr[j];
StringBuilder sub = new StringBuilder(tmp);
sub.setCharAt(1+3*j, tmp.charAt(3*j));
tmp = sub.toString();
arr[j] = tmp;
}
for (int j=3; j<6; j++) {
String tmp = arr[j];
StringBuilder sub = new StringBuilder(tmp);
sub.setCharAt(2+3*(j-3), tmp.charAt(1+3*(j-3)));
tmp = sub.toString();
arr[j] = tmp;
}
for (int j=6; j<8; j++) {
String tmp = arr[j];
StringBuilder sub = new StringBuilder(tmp);
sub.setCharAt(3+3*(j-6), tmp.charAt(2+3*(j-6)));
tmp = sub.toString();
arr[j] = tmp;
}
String tmp = arr[8];
StringBuilder sub = new StringBuilder(tmp);
sub.setCharAt(0, tmp.charAt(8));
tmp = sub.toString();
arr[8] = tmp;
for (int j=0; j<9; j++) {
sb.append(arr[j]+"\n");
}
System.out.println(sb.toString());
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
c22d78ee3aa0e8c86746f941c7687436
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static ArrayList<Integer>[] gr;
static boolean[] was;
static boolean[] want_h;
static int to;
static boolean ans;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
// br = new BufferedReader(new FileReader(new File("input.txt")));
// out = new PrintWriter(new File("output.txt"));
int PUTEN = nextInt();
for (int PUTIN_POMOGI = 0; PUTIN_POMOGI < PUTEN; PUTIN_POMOGI++) {
int[][] a = new int[9][9];
int[] b = new int[9];
int[] c = new int[9];
int n = 9;
for (int i = 0; i < 9; i++) {
char[] p = next().toCharArray();
for (int j = 0; j < 9; j++) {
a[i][j] = p[j] - '0';
}
}
b[0] = a[0][0];
c[0] = a[0][0];
b[1] = a[1][8];
c[1] = a[1][8];
b[2] = a[2][5];
c[2] = a[2][5];
b[3] = a[3][6];
c[3] = a[3][6];
b[4] = a[4][2];
c[4] = a[4][2];
b[5] = a[5][4];
c[5] = a[5][4];
b[6] = a[6][3];
c[6] = a[6][3];
b[7] = a[7][1];
c[7] = a[7][1];
b[8] = a[8][7];
c[8] = a[8][7];
for (int i = 0; i < n; i++) {
c[i] -= 1;
if (c[i] == 0) c[i] = 9;
}
a[0][0] = c[0];
a[1][8] = c[1];
a[2][5] = c[2];
a[3][6] = c[3];
a[4][2] = c[4];
a[5][4] = c[5];
a[6][3] = c[6];
a[7][1] = c[7];
a[8][7] = c[8];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.print(a[i][j]);
}
out.println();
}
}
out.close();
}
static BufferedReader br;
static PrintWriter out;
static StringTokenizer in = new StringTokenizer("");
static String next() throws IOException {
while (!in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
static int[] mix(int[] a) {
Random rnd = new Random();
for (int i = 1; i < a.length; i++) {
int j = rnd.nextInt(i);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static Double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static class sort implements Comparator<point> {
@Override
public int compare(point o1, point o2) {
return Integer.compare(o1.ind, o2.ind);
}
}
static void dfs(int from, String want) {
if (ans) return;
was[from] = true;
if (want_h[from] && want.equals("H")) ans = true;
if (!want_h[from] && want.equals("G")) ans = true;
for (int p : gr[from]) {
if (!was[p]) dfs(p, want);
}
return;
}
}
class point {
int ind;
int wight;
int speed;
public point(int ind, int wight, int speed) {
this.ind = ind;
this.wight = wight;
this.speed = speed;
}
}
// 915346876
// 624812539
// 183925764
// 457631928
// 296478153
// 579783416
// 822154397
// 341769275
// 641738592
// 872915349
// 915346872
// 624817539
// 183925764
// 457631928
// 296478153
// 579283416
// 862154397
// 341769285
// 641738592
// 872915346
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
662ea42577285707a99974e01de150ac
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class D{
public static void main(String[] args) throws IOException{
sc.init(System.in);
int T = sc.nextInt();
for(int t=0; t<T; ++t){
String A[] = new String[9];
for(int i=0; i<9; ++i){
String s = sc.next();
StringBuilder b = new StringBuilder();
for(int j=0; j<9; ++j){
char inp = s.charAt(j);
if(inp=='1')
b.append("2");
else
b.append(inp);
}
// b.append(s);
A[i] = b.toString();
}
for(int i=0; i<9; ++i){
System.out.println(A[i]);
}
}
}
}
class sc {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
b6cc0fb712d342f091ee5ff6607efb33
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// Scanner sc=new Scanner(System.in);
FastReader sc=new FastReader();
Writer w=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0){
String[] s=new String[9];
for(int i=0;i<9;i++){
s[i]=sc.next();
}
int d=0;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(d!=j)w.write(s[i].charAt(j));
else{
if(s[i].charAt(j)<'9')
w.write((char)(s[i].charAt(j)+1));
else w.write("1");
}
}
d+=3;
if(i==2)d=1;
if(i==5)d=2;
w.write("\n");
}
}
w.flush();
w.close();
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
33ffdf0fe1ac716587cb2dd080d24aca
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
// @uthor -: puneet
// TimeStamp -: 26/03/20
import java.io.*;
import java.util.*;
public class Q4 implements Runnable {
private boolean testCases=true;
private boolean console=false;
private long MOD = 1000_000_007L;
private int MAX = 1000_001;
char[][] arr=new char[9][];
void change(int i,int j){
if(arr[i][j]=='9'){
arr[i][j]='1';
}else{
// out.println(arr[i][j]-'0');
arr[i][j] = (char)('0'+(arr[i][j]-'0')+1);
}
}
public void solve() {
for(int i=0;i<9;++i){
arr[i] = in.ns().toCharArray();
}
change(0,0);
change(1,4);
change(2,8);
change(4,1);
change(5,5);
change(3,6);
change(8,2);
change(6,3);
change(7,7);
// arr[0][0] = '2';
// arr[1][4] = '2';
// arr[2][8] = '2';
//
// arr[4][1] = '2';
// arr[5][5] = '2';
// arr[3][6] = '2';
//
// arr[8][2] = '2';
// arr[6][3] = '2';
// arr[7][7] = '2';
for(int i=0;i<9;++i){
out.println(String.valueOf(arr[i]));
}
}
/* -------------------- Templates and Input Classes -------------------------------*/
@Override
public void run() {
try {
init();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int t= testCases ? in.ni() : 1;
while (t-->0) {
solve();
out.flush();
}
}
private FastInput in;
private PrintWriter out;
public static void main(String[] args) throws Exception {
// new Q4().run();
new Thread(null, new Q4(), "Main", 1 << 27).start();
}
private void init() throws FileNotFoundException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
try {
if (!console && System.getProperty("user.name").equals("puneet")) {
outputStream = new FileOutputStream("/home/puneet/Desktop/output.txt");
inputStream = new FileInputStream("/home/puneet/Desktop/input.txt");
}
} catch (Exception ignored) {
}
out = new PrintWriter(outputStream);
in = new FastInput(inputStream);
}
private void maualAssert(int a,int b,int c){
if(a<b || a>c)
throw new RuntimeException();
}
private void maualAssert(long a,long b,long c){
if(a<b || a>c)
throw new RuntimeException();
}
private void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int object : arr) list.add(object);
Collections.sort(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
public long ModPow(long x, long y, long MOD) {
long res = 1L;
x = x % MOD;
while (y >= 1) {
if ((y & 1) > 0) res = (res * x) % MOD;
x = (x * x) % MOD;
y >>= 1;
}
return res;
}
public int gcd(int a, int b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
static class FastInput { InputStream obj;
public FastInput(InputStream obj) {
this.obj = obj;
}
byte inbuffer[] = new byte[1024];
int lenbuffer = 0, ptrbuffer = 0;
int readByte() { if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) { ptrbuffer = 0;
try { lenbuffer = obj.read(inbuffer);
} catch (IOException e) { throw new InputMismatchException(); } }
if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; }
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();}
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(); }}
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 * 10L + (b - '0'); } else {
return minus ? -num : num; }b = readByte(); } }
boolean isSpaceChar(int c) {
return (!(c >= 33 && c <= 126));
}
int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; }
float nf() {return Float.parseFloat(ns());}
double nd() {return Double.parseDouble(ns());}
char nc() {return (char) skip();}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
deca2cc5871f4fed32f10135eb8406a1
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Cf182 implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Cf182(),"Main",1<<27).start();
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// array sorting by colm
public static void sortbyColumn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
// gcd
public static long findGCD(long arr[], int n)
{
long result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}
// fibonaci
static int fib(int n)
{
int a = 0, b = 1, c;
if (n == 0)
return a;
for (int i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}
// sort a string
public static String sortString(String inputString)
{
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// pair function
// list.add(new Pair<>(sc.nextInt(), i + 1));
// Collections.sort(list, (a, b) -> Integer.compare(b.first, a.first));
private static class Pair<F, S> {
private F first;
private S second;
public Pair() {}
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
public static HashMap<Long, Integer> sortByValue(HashMap<Long, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Long, Integer> > list =
new LinkedList<Map.Entry<Long, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Long, Integer> >() {
public int compare(Map.Entry<Long, Integer> o1,
Map.Entry<Long, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Long, Integer> temp = new LinkedHashMap<Long, Integer>();
for (Map.Entry<Long, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = sc.nextInt();
while(t--!=0)
{
String s[] = new String[9];
for(int i=0;i<9;i++)
s[i] = sc.next();
int c = 0;
for(int i=0;i<3;i++)
{
StringBuilder str = new StringBuilder(new String(s[i]));
str.replace(c, c+1,Character.toString(s[i].charAt(c+1)));
c += 3;
s[i] = str.toString();
}
c = 1;
for(int i=3;i<6;i++)
{
StringBuilder str = new StringBuilder(new String(s[i]));
str.replace(c, c+1,Character.toString(s[i].charAt(c+1)));
c += 3;
s[i] = str.toString();
}
c = 2;
for(int i=6;i<9;i++)
{
StringBuilder str = new StringBuilder(new String(s[i]));
str.replace(c, c+1,Character.toString(s[i].charAt(c-1)));
c += 3;
s[i] = str.toString();
}
for(int i=0;i<9;i++)
System.out.println(s[i]);
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
67df4ef500a3819cb14c8239bd525d3d
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.Scanner;
import java.util.*;
public class Power {
static long power(int a,int b){
if(b==0)
return 1;
long pow=power(a,b/2);
if(b%2!=0){
return pow*pow*a;
}
else{
return pow*pow;
}
}
static long gcd(long a,long b){
if(b==0)
return a;
else
return gcd(b,b%a);
}
static long lcm(long a,long b){
return (a*b)/gcd(a,b);
}
static List<Integer> primes(int n){
List<Integer> list=new ArrayList<Integer>();
boolean[] prime=new boolean[n+1];
Arrays.fill(prime,true);
prime[0]=false;
prime[1]=false;
int sqrt=(int)Math.sqrt(n);
for(int i=2;i<=sqrt;i++){
if(prime[i]){
for(int j=i*i;j<=n;j=j+i){
prime[j]=false;
}
}
}
for(int i=0;i<prime.length;i++){
if(prime[i])
list.add(i);
}
return list;
}
static long catalan(long n){
long result=0;
if(n<=1)
return 1;
for(long i=0;i<n;i++)
result+=catalan(i)*catalan(n-i-1);
return result;
}
static long totient(long n){
long res=0;
for(long i=1;i<=n;i++){
if(gcd(i,n)==1)
res++;
}
return res;
}
/* static double ternarysearch(long low,long high,long[] a,long[] b,long result){
int t=500;
while(t-->0 ){
long m1=low+(high-low)/3;
long m2=high-(high-low)/3;
long v1=ft(m1,a,b);
long v2=ft(m2,a,b);
result=Math.min(result,Math.min(v1,v2));
if(v1<result)
result=v1;
if(v2<result)
result=v2;
if(v1<v2){
high=m2;
}
else
low=m1;
}
for(long i=low;i<=high;i++){
// if(ft(i,a,b)<result)
// result=ft(i,a,b);
}
return result;
}*/
static int countone(Integer[] one,int low,int high){
if(low<=high){
int mid=(low+high)/2;
if((mid==high || one[mid+1]==0) && one[mid]==1)
return mid+1;
if(one[mid]==1){
return countone(one,mid+1,high);
}
else{
return countone(one,low,mid-1);
}
}
return 0;
}
static int countSol(int coeff[], int start,
int end, int rhs)
{
if (rhs == 0)
return 1;
int result = 0;
for (int i = start; i <= end; i++)
if (coeff[i] <= rhs)
result += countSol(coeff, i, end,
rhs - coeff[i]);
return result;
}
static int sol(int[] coeff,int n,int start,int end,int rhs){
coeff[0]=n;
return countSol(coeff, start, end, rhs);
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int test=input.nextInt();
input.nextLine();
while(test-->0){
for(int i=0;i<9;i++){
String s=input.next();
StringBuffer sb=new StringBuffer(s);
for(int j=0;j<sb.length();j++){
if(sb.charAt(j)=='2')
sb.replace(j,j+1,"1");
}
System.out.println(sb);
}
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
3eecef105a5cd64b9ce345005a02e119
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.Scanner;
public class AntiSudoku {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tests = sc.nextInt();
for(int t=0; t<tests; t++) {
String ans[] = new String[9];
int index = 0;
int row = 0;
for(int i=0; i<3; i++) {
String str1 = sc.next();
if(str1.charAt(index)=='9') {
str1 = str1.substring(0,index)+Integer.toString(1)+str1.substring(index+1,9);
}
else {
str1 = str1.substring(0,index)+Integer.toString(Integer.valueOf(str1.substring(index,index+1))+1)+str1.substring(index+1,9);
}
ans[row++]=str1;
index+=3;
}
index = 1;
for(int i=0; i<3; i++) {
String str1 = sc.next();
if(str1.charAt(index)=='9') {
str1 = str1.substring(0,index)+Integer.toString(1)+str1.substring(index+1,9);
}
else {
str1 = str1.substring(0,index)+Integer.toString(Integer.valueOf(str1.substring(index,index+1))+1)+str1.substring(index+1,9);
}
ans[row++]=str1;
index+=3;
}
index = 2;
for(int i=0; i<3; i++) {
String str1 = sc.next();
if(str1.charAt(index)=='9') {
str1 = str1.substring(0,index)+Integer.toString(1)+str1.substring(index+1,9);
}
else {
str1 = str1.substring(0,index)+Integer.toString(Integer.valueOf(str1.substring(index,index+1))+1)+str1.substring(index+1,9);
}
ans[row++]=str1;
index+=3;
}
for(int i=0; i<9; i++) {
System.out.println(ans[i]);
}
}
sc.close();
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
25cf3210e7b0934ea4e04a4187c486eb
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class D1335Unsolved {
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 FastReader input=new FastReader();
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("");
int[][] sudo=new int[9][9];
int[][] sec= {{0,0},{1,3},{2,6},{3,1},{4,4},{5,7},{6,2},{7,5},{8,8}};
int text=input.nextInt();
for(int t=0;t<text;++t){
//input.nextLine();
for(int i=0;i<9;++i){
String s=input.nextLine();
for(int j=0;j<9;++j){
sudo[i][j]=Integer.parseInt(String.valueOf(s.charAt(j)));
}
}
for(int i=0;i<9;++i){
if(sudo[sec[i][0]][sec[i][1]]<9){
sudo[sec[i][0]][sec[i][1]]++;
}else sudo[sec[i][0]][sec[i][1]]=1;
}
for(int i=0;i<9;++i){
for(int j=0;j<9;++j){
//System.out.print(sudo[i][j]);
sb.append(sudo[i][j]);
}
sb.append("\n");
}
}
System.out.println(sb);
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
1ca35e06f868f4877418d8b90a6c1dfd
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
//Scanner sc = new Scanner();
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
static int INF = (int)1e9;
static int maxn = 2*(int)1e5+5;
static int mod = 998244353 ;
static int n,m,t,q,d,k;
void solve(PrintWriter out, Reader in) throws IOException{
t = in.nextInt();
while (t--> 0) {
int[][] arr = new int[9][9];
for (int i = 0; i < 9; i++) {
String s = in.next();
for (int j = 0; j < 9; j++) {
arr[i][j] = s.charAt(j)-'0';
}
}
for (int i = 0; i < 9; i+=3) {
int itr = i/3;
int cnt = 0;
for (int j = itr; j < 9; j+=3) {
if (arr[i+cnt][j] == 3) arr[i+cnt][j] = 2;
else arr[i+cnt][j] = 3;
cnt ++;
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
out.print(arr[i][j]);
}
out.println();
}
}
}
//<>
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
807705a994491faf9f1f7ad5e84d737d
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class ProblemD {
public static PrintWriter out;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
//out = new PrintWriter(new BufferedOutputStream(System.out));
int cases = sc.nextInt();
int[][] ar = new int[9][9];
for (int x = 0; x < cases; x++) {
for (int i = 0; i < 9; i++) {
String str = sc.next();
for (int j = 0; j < 9; j++) {
ar[i][j] = str.charAt(j) - '0';
}
}
if (ar[0][8] == 9) { ar[0][8] = 8; }
else {ar[0][8] += 1; }
if (ar[1][5] == 9) { ar[1][5] = 8; }
else {ar[1][5] += 1; }
if (ar[2][2] == 9) { ar[2][2] = 8; }
else {ar[2][2] += 1; }
if (ar[3][7] == 9) { ar[3][7] = 8; }
else {ar[3][7] += 1; }
if (ar[4][3] == 9) { ar[4][3] = 8; }
else {ar[4][3] += 1; }
if (ar[5][0] == 9) { ar[5][0] = 8; }
else {ar[5][0] += 1; }
if (ar[6][1] == 9) { ar[6][1] = 8; }
else {ar[6][1] += 1; }
if (ar[7][6] == 9) { ar[7][6] = 8; }
else {ar[7][6] += 1; }
if (ar[8][4] == 9) { ar[8][4] = 8; }
else {ar[8][4] += 1; }
for (int i = 0; i < 9; i++) {
StringBuilder s = new StringBuilder();
for (int j = 0; j < 9; j++) {
s.append(ar[i][j]);
}
System.out.println(s.toString());
}
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
33dc6619bd5655f3b40a62f5d9ca8fe4
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
sc.nextLine();
while(t-->0)
{
int i;
for(i=0;i<9;i++)
{
String str=sc.nextLine();
str=str.replace('1','2');
System.out.println(str);
}
}
sc.close();
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
baaaf9285b1ecb43f7aba5f948b069ff
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class HelloWorld{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
input.nextInt();
while(input.hasNext()){
for(int i=0;i<9;i++){
String st=input.next();
StringBuilder s=new StringBuilder();
for(int j=0;j<st.length();j++){
if(j==(i/3)+3*(i%3)){
int t=Integer.parseInt(st.substring(j, j+1));
if(t==9){
s.append('1');
continue;
}
if(t<9){
s.append(Integer.toString(t+1));
continue;
}
}
s.append(st.charAt(j));
}
System.out.println(s.toString());
}
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
a7bc7bee5b023b4d69012929aa3ee35f
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws Exception
{
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader sc = new BufferedReader(r);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = Integer.parseInt(sc.readLine());
for(int k=0;k<t;k++){
//String s[]=new String[9];
//int a[][]=new int[9][9];
String s[]=new String[9];
for(int i=0;i<9;i++){
s[i]=sc.readLine();
}
for(int i=0;i<9;i++){
s[i]=s[i].replace("9","1");
System.out.print(s[i]);
System.out.println("");
}
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
23a9cec4e77e1b3dd0a889cc6435ae57
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
public class AntiSudoku{
static Scanner in=new Scanner(System.in);
public static void main(String array[]){
int t=in.nextInt();
while(t-->0){
StringBuffer sudoku[]=new StringBuffer[9];
for(int i=0;i<9;i++){
sudoku[i]=new StringBuffer(in.next());
}
for(int i=0;i<9;i++){
int j=sudoku[i].indexOf("2");
sudoku[i].replace(j,j+1,"1");
System.out.println(sudoku[i]);
}
}
}
}
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
2a5132bb02ecb2b122eb0244432db1e0
|
train_001.jsonl
|
1586788500
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-->0) {
for (int i = 1; i <=9;i++) {
String s = sc.nextLine();
int idx = s.indexOf('1');
System.out.println(s.substring(0, idx) + 2 + s.substring(idx+1));
}
}
}
private static void solve(int n, int a, int b) {
StringBuilder sb = new StringBuilder();
char max = (char)('a' + b - 1);
char s = 'a';
sb.append(s);
for (int i = 1; i <n;i++) {
s = get(s, max);
sb.append(s);
}
System.out.println(sb.toString());
}
/**
*
* a b c a b a c
*
*
*
*/
private static char get(char c, char max) {
if (c == max) return 'a';
else return (char)(c+1);
}
private static char getNext(char c) {
if (c == 'z') return 'a';
else return (char)(c+1);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
/**
*x=3
* 1 1 2 5
*/
/**
*
* 1+1
**/
|
Java
|
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
|
2 seconds
|
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
| null |
Java 11
|
standard input
|
[
"constructive algorithms",
"implementation"
] |
0e21f1c48c8c0463b2ffa7275eddc633
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
| 1,300 |
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
|
standard output
| |
PASSED
|
b2bc05820550935ab2d3775fa596a6b1
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.util.Scanner;
// 2500
public class CrosswordExpert1194F {
static final long MOD = 1_000_000_007;
static long n;
static long T;
static long[] t; // [0] = 0, [1:] = input, [n + 1] = T
public static void main(String[] args) throws Exception {
try (Scanner scanner = new Scanner(System.in)) {
n = scanner.nextLong();
T = scanner.nextLong();
t = new long[(int) n + 2];
t[(int) n + 1] = T;
for (int i = 1; i <= n; i++) t[i] = scanner.nextLong();
System.out.println(mean());
}
}
static long mean() {
long res = 0;
long sum = 0;
// choose(x, y) = x! / (y! * (x - y)!)
// choose(x, y - 1) = choose(x, y) * y / (x - y + 1)
// choose(x + 1, y) = choose(x, y) * (x + 1) / (x - y + 1)
// choose(x + 1, y + 1) = choose(x, y) * (x + 1) / (y + 1)
long choose = 1; // choose(x, y)
for (int x = 0, y = 0; x <= n && y >= 0;) {
if (sum + time(x + 1, y + 1) <= T) {
sum += time(x + 1, 0);
choose = mul(choose, x + 1, pow(y + 1, -1));
x++;
y++;
} else if (sum + time(x + 1, y) <= T) {
res = add(res, mul(x, pow(2, -x - 1), choose));
sum += time(x + 1, 0);
choose = mul(choose, x + 1, pow(x - y + 1, -1));
x++;
} else {
res = add(res, mul(x, pow(2, -x), choose));
choose = mul(choose, y, pow(x - y + 1, -1));
y--;
}
}
return res;
}
static long time(int x, int y) {
return t[x] + y;
}
static long mod(long a) {
return a < 0 ? mod(a + MOD)
: a < MOD ? a
: a % MOD;
}
static long add(long a, long b) {
return mod(a + b);
}
static long mul(long a, long b) {
return mod(mod(a) * mod(b));
}
static long mul(long... values) {
long res = 1;
for (long v : values) res = mul(res, v);
return res;
}
static long pow(long a, long b) {
if (b < 0) return pow(a, MOD + b - 1);
long n = b;
long x = a;
long res = 1;
while (n > 0) {
if ((n & 1) != 0) res = mul(res, x);
x = mul(x, x);
n >>= 1;
}
return res;
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
904be0454090aa6ae363e02f8b8d169a
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
/**
* author: derrick20
* created: 10/3/20 12:50 AM
*/
import java.io.*;
import java.util.*;
public class CrosswordExpertBruteForce implements Runnable {
public static void main(String[] args) throws Exception {
new Thread(null, new CrosswordExpertBruteForce(), ": )", 1 << 28).start();
}
public void run() {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
long T = sc.nextLong();
long[] prefix = new long[N + 1];
long[] time = new long[N + 1];
int puzzles = 0;
for (int i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1] + (time[i] = sc.nextLong());
if (prefix[i] <= T) {
puzzles = i;
}
}
int MAX = (int) 2e5; // todo change this!
fact = new long[MAX + 1];
invFact = new long[MAX + 1];
long[] twoPowInv = new long[MAX + 1];
fact[0] = 1;
invFact[0] = 1;
twoPowInv[0] = 1;
long twoInv = fastExpo(2, mod - 2);
for (int i = 1; i <= MAX; i++) {
fact[i] = ((long) i * fact[i - 1]) % mod;
invFact[i] = inv(fact[i]);
twoPowInv[i] = (twoInv * twoPowInv[i - 1]) % mod;
}
long ways = 0;
int minOnes = 0;
int maxOnes = (int) Math.min(puzzles, T - prefix[puzzles]);
for (int ct = minOnes; ct <= maxOnes; ct++) {
ways = (ways + choose(puzzles, ct)) % mod;
}
long EV = mult(puzzles, mult(ways, twoPowInv[puzzles]));
puzzles--;
while (puzzles >= 1) {
if (prefix[puzzles + 1] + puzzles < T) {
// With the current number of puzzles, we can still
// fit the next puzzle in, so this amount is impossible.
break;
}
// Otherwise, it's possible
minOnes = (int) Math.min(T - prefix[puzzles + 1], puzzles);
maxOnes = (int) Math.min(T - prefix[puzzles], puzzles);
long waysReg = 0;
// System.out.println("Puzzles = " + puzzles + " min = " + minOnes + " max = " + maxOnes);
for (int ct = minOnes + 1; ct <= maxOnes; ct++) {
waysReg = add(waysReg, choose(puzzles, ct));
}
long waysExtra = choose(puzzles, minOnes);
long contrib = add(mult(waysReg, twoPowInv[puzzles]), mult(waysExtra, twoPowInv[puzzles + 1]));
contrib = mult(puzzles, contrib);
EV = add(EV, contrib);
puzzles--;
}
out.println(EV);
out.close();
}
// todo SET THE MOD
static long mod = (long) 1e9 + 7;
static long[] fact, invFact;
static long mult(long a, long b) {
return (a * b) % mod;
}
static long add(long a, long b) {
long ans = a + b;
if (ans >= mod) {
ans -= mod;
}
return ans;
}
static long choose(int n, int k) {
if (k > n) return 0; // this works in THIS PROBLEM
long ans = (fact[n] * invFact[n - k]) % mod;
return (ans * invFact[k]) % mod;
}
static long inv(long x) {
return fastExpo(x, mod - 2);
}
static long fastExpo(long x, long k) {
long ans = 1;
long bit = x;
while (k > 0) {
if (k % 2 == 1) {
ans = (bit * ans) % mod;
}
bit = (bit * bit) % mod;
k /= 2;
}
return ans;
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
d98b12c33676fcabc6d78a584610d277
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
/**
* author: derrick20
* created: 10/3/20 12:50 AM
*/
import java.io.*;
public class CrosswordExpertSimple implements Runnable {
public static void main(String[] args) throws Exception {
new Thread(null, new CrosswordExpertSimple(), ": )", 1 << 28).start();
}
public void run() {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
setupCombo((int) 2e5 + 1);
int N = sc.nextInt();
long T = sc.nextLong();
long[] time = new long[N + 2];
for (int i = 1; i <= N; i++) {
time[i] = sc.nextLong();
}
time[N + 1] = T + 1;
long EV = 0;
long prefix = time[1];
for (int puzzles = 1; puzzles <= N; puzzles++, prefix += time[puzzles]) {
if (prefix + time[puzzles + 1] + puzzles < T || prefix > T) {
// With the current number of puzzles, we can still
// fit the next puzzle in, so this amount is impossible.
continue;
}
for (int extra = 0; extra <= 1; extra++) {
// KEY idea: prefix + ones <= T, but also T < prefix + next + ones + extra
// the strict inequality ensures that it cannot fit. We can either put an extra
// 1 there, or not, but that case still contributes to us being able to have
// the full [puzzles] chunk
// -> ones <= T - prefix,
// -> ones > T - prefix - next - extra
// also, we have the standard bounds 0 <= ones <= puzzles
/*
Intuition. We need enough to keep out the next one (potentially expanded by 1)
So we need 1 more than the amount that would let it fit perfectly. We also can't
go beyond the amount that would allow the current amount fit.
The runtime perfectly works out because we only cover disjoint sets of positions
that are bounded by N
*/
int minOnes = (int) Math.max(0, T - prefix - time[puzzles + 1] - extra + 1);
if (minOnes > puzzles) continue; // not enough
int maxOnes = (int) Math.max(0, Math.min(T - prefix, puzzles));
// System.out.println("Puzzles = " + puzzles + " min = " + minOnes + ", max = " + maxOnes + " extra = " + extra);
for (int ones = minOnes; ones <= maxOnes; ones++) {
EV = add(EV, mult(puzzles, mult(twoPowInv[puzzles + 1], choose(puzzles, ones))));
}
}
// System.out.println("At puzzles = " + puzzles + " EV = " + EV);
}
out.println(EV);
out.close();
}
// todo SET THE MOD
static long mod = (long) 1e9 + 7;
static long[] fact, invFact, twoPowInv;
static void setupCombo(int MAX) {
fact = new long[MAX + 1];
invFact = new long[MAX + 1];
twoPowInv = new long[MAX + 1];
fact[0] = 1;
invFact[0] = 1;
twoPowInv[0] = 1;
long twoInv = fastExpo(2, mod - 2);
for (int i = 1; i <= MAX; i++) {
fact[i] = ((long) i * fact[i - 1]) % mod;
invFact[i] = inv(fact[i]);
twoPowInv[i] = (twoInv * twoPowInv[i - 1]) % mod;
}
}
static long mult(long a, long b) {
return (a * b) % mod;
}
static long add(long a, long b) {
long ans = a + b;
if (ans >= mod) {
ans -= mod;
}
return ans;
}
static long choose(int n, int k) {
if (k > n) return 0; // this works in THIS PROBLEM
long ans = (fact[n] * invFact[n - k]) % mod;
return (ans * invFact[k]) % mod;
}
static long inv(long x) {
return fastExpo(x, mod - 2);
}
static long fastExpo(long x, long k) {
long ans = 1;
long bit = x;
while (k > 0) {
if (k % 2 == 1) {
ans = (bit * ans) % mod;
}
bit = (bit * bit) % mod;
k /= 2;
}
return ans;
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
81a4c2a8b171a5b4c252e9555f3ca679
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class CrosswordExpert {
public static long MOD = 1000000007;
public static int MAXN = 200005;
public static long[] fact;
public static long[] invfact;
public static void main(String[] args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
long t = Long.parseLong(st.nextToken());
fact = new long[MAXN];
invfact = new long[MAXN];
fact[0] = 1;
invfact[0] = 1;
for(int i = 1; i < MAXN; i++){
fact[i] = (fact[i-1]*i)%MOD;
invfact[i] = pow(fact[i], MOD-2, MOD);
}
long expVal = 0;
long INV2 = pow(2, MOD-2, MOD);
long mult = 1;
long[] arr = new long[n];
st = new StringTokenizer(f.readLine());
for(int i = 0; i < n; i++){
arr[i] = Long.parseLong(st.nextToken())+1;
}
long sum = 0;
int ptr = 0;
while(ptr < n && sum+arr[ptr] <= t){
sum+=arr[ptr];
ptr++;
mult*=INV2;
mult%=MOD;
}
for(int i = 0; i <= ptr; i++){
long prob = (ncr(ptr, i)*mult)%MOD;
long toAdd = (prob*ptr)%MOD;
if(ptr != n && sum+arr[ptr]-1 == t) toAdd = (toAdd*INV2)%MOD;
expVal+=toAdd;
expVal%=MOD;
sum--;
if(ptr != n && sum+arr[ptr] <= t){
sum+=arr[ptr];
ptr++;
mult*=INV2;
mult%=MOD;
}
}
out.println(expVal);
out.close();
}
public static long ncr(int n, int r){
if(n < r) return 0;
if(r < 0) return 0;
if(n < 0) return 0;
return(((fact[n]*invfact[r])%MOD*invfact[n-r])%MOD);
}
public static long pow(long x, long y, long p){
long res = 1;
x = x % p;
if (x == 0) return 0;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
fc246df55ceaa4ffbc1eb4513c6e5ad4
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
static final int mod = 1000000007;
int[] fact;
int[] ifact;
int pow(int x, int n) {
int res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) {
if ((n & 1) != 0) {
res = (int) (res * p % mod);
}
}
return res;
}
int C(int n, int k) {
if (n < 0 || k < 0 || n < k) return 0;
return (int) ((fact[n] * (ifact[k] * (long) ifact[n - k] % mod)) % mod);
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
long t = in.nextLong();
long[] T = new long[n + 1];
for (int i = 1; i <= n; i++) {
T[i] = in.nextLong();
T[i] += T[i - 1];
}
fact = new int[n + 1];
ifact = new int[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++)
fact[i] = (int) ((fact[i - 1] * (long) i) % mod);
for (int i = 0; i <= n; i++) ifact[i] = pow(fact[i], mod - 2);
long ans = 0;
int v = (mod + 1) / 2;
int inv2 = v;
for (int i = 1; i <= n; i++) {
long mx = t - T[i];
int mn = i == n ? 0 : Integer.max(0, (int) Long.min(n, t - T[i + 1] + 1));
if (mx < 0) break;
long sm = 0;
for (int j = mn; j <= mx && j <= i; j++) {
sm += C(i, j);
}
sm %= mod;
ans += (sm * (i * (long) v % mod)) % mod;
v = (int) ((v * (long) inv2) % mod);
if (mn - 1 <= mx && mn - 1 >= 0 && mn - 1 <= i) {
ans += (C(i, mn - 1) * (long) v % mod) * (long) i % mod;
}
ans %= mod;
}
out.println((ans % mod + mod) % mod);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
8dbda9f815a2a9d1a02f246cacacef9b
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;
public class CFContest {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
public void solve() {
int n = io.readInt();
long t = io.readLong();
NumberTheory.Modular mod = new NumberTheory.Modular((int) 1e9 + 7);
NumberTheory.Composite comp = new NumberTheory.Composite(n, mod);
int[] f = new int[n + 1];
long[] sums = new long[n + 1];
for (int i = 1; i <= n; i++) {
sums[i] = sums[i - 1] + io.readInt();
}
int trace = 1;
int x = 0;
int y = n;
for (int i = 1; i <= n && sums[i] <= t; i++) {
trace = mod.mul(2, trace);
trace = mod.plus(trace, -comp.composite(x, y));
x++;
long remain = t - sums[i];
while (remain < y) {
trace = mod.plus(trace, -comp.composite(x, y));
y--;
}
f[i] = trace;
}
int exp = 0;
int inv2 = (mod.m + 1) / 2;
int inv2Exp = 1;
for (int i = 1; i <= n; i++) {
inv2Exp = mod.mul(inv2Exp, inv2);
exp = mod.plus(exp, mod.mul(f[i], inv2Exp));
}
io.cache.append(exp);
}
}
public static class NumberTheory {
/**
* Mod operations
*/
public static class Modular {
int m;
public Modular(int m) {
this.m = m;
}
public int valueOf(int x) {
x %= m;
if (x < 0) {
x += m;
}
return x;
}
public int valueOf(long x) {
x %= m;
if (x < 0) {
x += m;
}
return (int) x;
}
public int mul(int x, int y) {
return valueOf((long) x * y);
}
public int mul(long x, long y) {
x = valueOf(x);
y = valueOf(y);
return valueOf(x * y);
}
public int plus(int x, int y) {
return valueOf(x + y);
}
public int plus(long x, long y) {
x = valueOf(x);
y = valueOf(y);
return valueOf(x + y);
}
@Override
public String toString() {
return "mod " + m;
}
}
/**
* Bit operations
*/
public static class BitOperator {
public int bitAt(int x, int i) {
return (x >> i) & 1;
}
public int bitAt(long x, int i) {
return (int) ((x >> i) & 1);
}
public int setBit(int x, int i, boolean v) {
if (v) {
x |= 1 << i;
} else {
x &= ~(1 << i);
}
return x;
}
public long setBit(long x, int i, boolean v) {
if (v) {
x |= 1L << i;
} else {
x &= ~(1L << i);
}
return x;
}
/**
* Determine whether x is subset of y
*/
public boolean subset(long x, long y) {
return intersect(x, y) == x;
}
/**
* Merge two set
*/
public long merge(long x, long y) {
return x | y;
}
public long intersect(long x, long y) {
return x & y;
}
public long differ(long x, long y) {
return x - intersect(x, y);
}
}
/**
* Power operations
*/
public static class Power {
final Modular modular;
public Power(Modular modular) {
this.modular = modular;
}
public int pow(int x, long n) {
if (n == 0) {
return 1;
}
long r = pow(x, n >> 1);
r = modular.valueOf(r * r);
if ((n & 1) == 1) {
r = modular.valueOf(r * x);
}
return (int) r;
}
public int inverse(int x) {
return pow(x, modular.m - 2);
}
public int pow2(int x) {
return x * x;
}
public long pow2(long x) {
return x * x;
}
public double pow2(double x) {
return x * x;
}
}
/**
* Log operations
*/
public static class Log2 {
public int ceilLog(int x) {
return 32 - Integer.numberOfLeadingZeros(x - 1);
}
public int floorLog(int x) {
return 31 - Integer.numberOfLeadingZeros(x);
}
public int ceilLog(long x) {
return 64 - Long.numberOfLeadingZeros(x - 1);
}
public int floorLog(long x) {
return 63 - Long.numberOfLeadingZeros(x);
}
}
/**
* Find all inverse number
*/
public static class InverseNumber {
int[] inv;
public InverseNumber(int[] inv, int limit, Modular modular) {
this.inv = inv;
inv[1] = 1;
int p = modular.m;
for (int i = 2; i <= limit; i++) {
int k = p / i;
int r = p % i;
inv[i] = modular.mul(-k, inv[r]);
}
}
public InverseNumber(int limit, Modular modular) {
this(new int[limit + 1], limit, modular);
}
}
/**
* Factorial
*/
public static class Factorial {
int[] fact;
int[] inv;
public Factorial(int[] fact, int[] inv, InverseNumber in, int limit, Modular modular) {
this.fact = fact;
this.inv = inv;
fact[0] = inv[0] = 1;
for (int i = 1; i <= limit; i++) {
fact[i] = modular.mul(fact[i - 1], i);
inv[i] = modular.mul(inv[i - 1], in.inv[i]);
}
}
public Factorial(int limit, Modular modular) {
this(new int[limit + 1], new int[limit + 1], new InverseNumber(limit, modular), limit, modular);
}
}
/**
* Composition
*/
public static class Composite {
final Factorial factorial;
final Modular modular;
public Composite(Factorial factorial, Modular modular) {
this.factorial = factorial;
this.modular = modular;
}
public Composite(int limit, Modular modular) {
this(new Factorial(limit, modular), modular);
}
public int composite(int m, int n) {
if (n > m) {
return 0;
}
return modular.mul(modular.mul(factorial.fact[m], factorial.inv[n]), factorial.inv[m - n]);
}
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder();
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 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() {
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
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
24f944452538ff403f8c3e01daedc4db
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.function.IntPredicate;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
private static final NumberTheory.Mod107 mod = new NumberTheory.Mod107();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long T = in.nextLong();
int[] t = in.readIntArray(n);
long[] cumT = new long[n + 1];
for (int i = 0; i < n; i++) {
cumT[i + 1] = cumT[i] + t[i];
}
int min = -1 + BinarySearch.binarySearch(count -> {
if (count < 0)
return false;
if (count > n)
return true;
return cumT[count] + count > T;
});
int max = -1 + BinarySearch.binarySearch(count -> {
if (count < 0)
return false;
if (count > n)
return true;
return cumT[count] > T;
});
long[] invPow2 = new long[max + 2];
long inv2 = mod.inv(2);
invPow2[0] = 1;
for (int i = 0; i + 1 < invPow2.length; i++) {
invPow2[i + 1] = mod.mult(invPow2[i], inv2);
}
long answer = min - 1;
int mostBad = min;
long pr = 0;
for (int i = 0; i <= mostBad; i++) {
pr = mod.add(pr, mod.mult(mod.ncr(min, i), invPow2[min]));
}
for (int count = min; count <= max; count++) {
int mostBadTarget = (int) (T - cumT[count]);
while (mostBad > mostBadTarget) {
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count]));
mostBad--;
}
answer = mod.add(answer, pr);
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count + 1]));
}
out.println(answer);
}
}
static class InputReader {
public final BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
static class NumberTheory {
private static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
final ArrayList<Long> factorial = new ArrayList<>();
final ArrayList<Long> invFactorial = new ArrayList<>();
public abstract long modulus();
public Modulus() {
super();
factorial.add(1L);
invFactorial.add(1L);
}
public long fact(int n) {
while (factorial.size() <= n) {
factorial.add(mult(factorial.get(factorial.size() - 1), factorial.size()));
}
return factorial.get(n);
}
public long fInv(int n) {
int lastKnown = invFactorial.size() - 1;
if (lastKnown < n) {
long[] fInv = new long[n - lastKnown];
fInv[0] = inv(fact(n));
for (int i = 1; i < fInv.length; i++) {
fInv[i] = mult(fInv[i - 1], n - i + 1);
}
for (int i = fInv.length - 1; i >= 0; i--) {
invFactorial.add(fInv[i]);
}
}
return invFactorial.get(n);
}
public long ncr(int n, int r) {
ASSERT(n >= 0);
if (r < 0 || n < r)
return 0;
return mult(fact(n), mult(fInv(r), fInv(n - r)));
}
public long normalize(long x) {
x %= modulus();
if (x < 0)
x += modulus();
return x;
}
public long add(long a, long b) {
long v = a + b;
return v < modulus() ? v : v - modulus();
}
public long subtract(long a, long b) {
long v = a - b;
return v < 0 ? v + modulus() : v;
}
public long mult(long a, long b) {
return (a * b) % modulus();
}
public long inv(long value) {
long g = modulus(), x = 0, y = 1;
for (long r = value; r != 0; ) {
long q = g / r;
g %= r;
long temp = g;
g = r;
r = temp;
x -= q * y;
temp = x;
x = y;
y = temp;
}
ASSERT(g == 1);
ASSERT(y == modulus() || y == -modulus());
return normalize(x);
}
}
public static class Mod107 extends NumberTheory.Modulus<NumberTheory.Mod107> {
public long modulus() {
return 1_000_000_007L;
}
}
}
static class BinarySearch {
public static int binarySearch(IntPredicate bigEnough) {
int tooSmall = 0, tooBig;
if (bigEnough.test(tooSmall)) {
return tooSmall;
}
for (tooBig = 1; !bigEnough.test(tooBig); tooBig *= 2)
;
if (!bigEnough.test(tooBig - 1)) {
return tooBig;
}
while (tooBig - tooSmall > 1) {
int center = tooSmall + (tooBig - tooSmall) / 2;
if (!bigEnough.test(center)) {
tooSmall = center;
} else {
tooBig = center;
}
}
return tooBig;
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
49219f24e709421e145804664a4009c7
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
private static final NumberTheory.Mod107 mod = new NumberTheory.Mod107();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long T = in.nextLong();
int[] t = in.readIntArray(n);
long[] cumT = new long[n + 1];
int min = -1, max = -1;
for (int i = 0; i < n; i++) {
cumT[i + 1] = cumT[i] + t[i];
if (min == -1 && cumT[i + 1] + (i + 1) > T)
min = i;
if (max == -1 && cumT[i + 1] > T)
max = i;
}
if (min == -1)
min = 0;
if (max == -1)
max = n;
long[] invPow2 = new long[max + 2 - min];
long inv2 = mod.inv(2);
invPow2[0] = mod.pow(inv2, min);
for (int i = 0; i + 1 < invPow2.length; i++) {
invPow2[i + 1] = mod.mult(invPow2[i], inv2);
}
long answer = min - 1;
int mostBad = min;
long pr = 0;
for (int i = 0; i <= mostBad; i++) {
pr = mod.add(pr, mod.mult(mod.ncr(min, i), invPow2[0]));
}
for (int count = min; count <= max; count++) {
int mostBadTarget = (int) (T - cumT[count]);
while (mostBad > mostBadTarget) {
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count - min]));
mostBad--;
}
answer = mod.add(answer, pr);
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count + 1 - min]));
}
out.println(answer);
}
}
static class InputReader {
public final BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
static class NumberTheory {
private static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
final ArrayList<Long> factorial = new ArrayList<>();
final ArrayList<Long> invFactorial = new ArrayList<>();
public abstract long modulus();
public Modulus() {
super();
factorial.add(1L);
invFactorial.add(1L);
}
public long fact(int n) {
while (factorial.size() <= n) {
factorial.add(mult(factorial.get(factorial.size() - 1), factorial.size()));
}
return factorial.get(n);
}
public long fInv(int n) {
int lastKnown = invFactorial.size() - 1;
if (lastKnown < n) {
long[] fInv = new long[n - lastKnown];
fInv[0] = inv(fact(n));
for (int i = 1; i < fInv.length; i++) {
fInv[i] = mult(fInv[i - 1], n - i + 1);
}
for (int i = fInv.length - 1; i >= 0; i--) {
invFactorial.add(fInv[i]);
}
}
return invFactorial.get(n);
}
public long ncr(int n, int r) {
ASSERT(n >= 0);
if (r < 0 || n < r)
return 0;
return mult(fact(n), mult(fInv(r), fInv(n - r)));
}
public long normalize(long x) {
x %= modulus();
if (x < 0)
x += modulus();
return x;
}
public long add(long a, long b) {
long v = a + b;
return v < modulus() ? v : v - modulus();
}
public long subtract(long a, long b) {
long v = a - b;
return v < 0 ? v + modulus() : v;
}
public long mult(long a, long b) {
return (a * b) % modulus();
}
public long pow(long x, int e) {
if (e < 0) {
x = inv(x);
e *= -1;
}
if (e == 0)
return 1;
if ((e & 1) > 0)
return mult(x, pow(x, e - 1));
return pow(mult(x, x), e / 2);
}
public long inv(long value) {
long g = modulus(), x = 0, y = 1;
for (long r = value; r != 0; ) {
long q = g / r;
g %= r;
long temp = g;
g = r;
r = temp;
x -= q * y;
temp = x;
x = y;
y = temp;
}
ASSERT(g == 1);
ASSERT(y == modulus() || y == -modulus());
return normalize(x);
}
}
public static class Mod107 extends NumberTheory.Modulus<NumberTheory.Mod107> {
public long modulus() {
return 1_000_000_007L;
}
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
51be5da0418b81778fe668ed5946cd4f
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
private static final NumberTheory.Mod107 mod = new NumberTheory.Mod107();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long T = in.nextLong();
int[] t = in.readIntArray(n);
long[] cumT = new long[n + 1];
int min = -1, max = -1;
for (int i = 0; i < n; i++) {
cumT[i + 1] = cumT[i] + t[i];
if (min == -1 && cumT[i + 1] + (i + 1) > T)
min = i;
if (max == -1 && cumT[i + 1] > T)
max = i;
}
if (min == -1)
min = 0;
if (max == -1)
max = n;
long[] invPow2 = new long[max + 2 - min];
long inv2 = mod.inv(2);
invPow2[0] = mod.pow(inv2, min);
for (int i = 0; i + 1 < invPow2.length; i++) {
invPow2[i + 1] = mod.mult(invPow2[i], inv2);
}
long answer = min - 1;
int mostBad = min;
long pr = 0;
for (int i = 0; i <= mostBad; i++) {
pr = mod.add(pr, mod.ncr(min, i));
}
pr = mod.mult(pr, invPow2[0]);
for (int count = min; count <= max; count++) {
int mostBadTarget = (int) (T - cumT[count]);
long subtract = 0;
while (mostBad > mostBadTarget) {
subtract = mod.add(subtract, mod.ncr(count, mostBad));
mostBad--;
}
pr = mod.subtract(pr, mod.mult(subtract, invPow2[count - min]));
answer = mod.add(answer, pr);
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count + 1 - min]));
}
out.println(answer);
}
}
static class InputReader {
public final BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
static class NumberTheory {
private static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
final ArrayList<Long> factorial = new ArrayList<>();
final ArrayList<Long> invFactorial = new ArrayList<>();
public abstract long modulus();
public Modulus() {
super();
factorial.add(1L);
invFactorial.add(1L);
}
public long fact(int n) {
while (factorial.size() <= n) {
factorial.add(mult(factorial.get(factorial.size() - 1), factorial.size()));
}
return factorial.get(n);
}
public long fInv(int n) {
int lastKnown = invFactorial.size() - 1;
if (lastKnown < n) {
long[] fInv = new long[n - lastKnown];
fInv[0] = inv(fact(n));
for (int i = 1; i < fInv.length; i++) {
fInv[i] = mult(fInv[i - 1], n - i + 1);
}
for (int i = fInv.length - 1; i >= 0; i--) {
invFactorial.add(fInv[i]);
}
}
return invFactorial.get(n);
}
public long ncr(int n, int r) {
ASSERT(n >= 0);
if (r < 0 || n < r)
return 0;
return mult(fact(n), mult(fInv(r), fInv(n - r)));
}
public long normalize(long x) {
x %= modulus();
if (x < 0)
x += modulus();
return x;
}
public long add(long a, long b) {
long v = a + b;
return v < modulus() ? v : v - modulus();
}
public long subtract(long a, long b) {
long v = a - b;
return v < 0 ? v + modulus() : v;
}
public long mult(long a, long b) {
return (a * b) % modulus();
}
public long pow(long x, int e) {
if (e < 0) {
x = inv(x);
e *= -1;
}
if (e == 0)
return 1;
if ((e & 1) > 0)
return mult(x, pow(x, e - 1));
return pow(mult(x, x), e / 2);
}
public long inv(long value) {
long g = modulus(), x = 0, y = 1;
for (long r = value; r != 0; ) {
long q = g / r;
g %= r;
long temp = g;
g = r;
r = temp;
x -= q * y;
temp = x;
x = y;
y = temp;
}
ASSERT(g == 1);
ASSERT(y == modulus() || y == -modulus());
return normalize(x);
}
}
public static class Mod107 extends NumberTheory.Modulus<NumberTheory.Mod107> {
public long modulus() {
return 1_000_000_007L;
}
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
fc8dfbd9fe6c280d59986207ec591d46
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
private static final NumberTheory.Mod107 mod = new NumberTheory.Mod107();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long T = in.nextLong();
int[] t = in.readIntArray(n);
long[] cumT = new long[n + 1];
int min = -1, max = -1;
for (int i = 0; i < n; i++) {
cumT[i + 1] = cumT[i] + t[i];
if (min == -1 && cumT[i + 1] + (i + 1) > T)
min = i;
if (max == -1 && cumT[i + 1] > T)
max = i;
}
if (min == -1)
min = 0;
if (max == -1)
max = n;
long[] invPow2 = new long[max + 2 - min];
long inv2 = mod.inv(2);
invPow2[0] = mod.pow(inv2, min);
for (int i = 0; i + 1 < invPow2.length; i++) {
invPow2[i + 1] = mod.mult(invPow2[i], inv2);
}
long answer = min - 1;
int mostBad = min;
long pr = 0;
for (int i = 0; i <= mostBad; i++) {
pr = mod.add(pr, mod.ncr(min, i));
}
pr = mod.mult(pr, invPow2[0]);
for (int count = min; count <= max; count++) {
int mostBadTarget = (int) (T - cumT[count]);
while (mostBad > mostBadTarget) {
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count - min]));
mostBad--;
}
answer = mod.add(answer, pr);
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count + 1 - min]));
}
out.println(answer);
}
}
static class InputReader {
public final BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
static class NumberTheory {
private static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
final ArrayList<Long> factorial = new ArrayList<>();
final ArrayList<Long> invFactorial = new ArrayList<>();
public abstract long modulus();
public Modulus() {
super();
factorial.add(1L);
invFactorial.add(1L);
}
public long fact(int n) {
while (factorial.size() <= n) {
factorial.add(mult(factorial.get(factorial.size() - 1), factorial.size()));
}
return factorial.get(n);
}
public long fInv(int n) {
int lastKnown = invFactorial.size() - 1;
if (lastKnown < n) {
long[] fInv = new long[n - lastKnown];
fInv[0] = inv(fact(n));
for (int i = 1; i < fInv.length; i++) {
fInv[i] = mult(fInv[i - 1], n - i + 1);
}
for (int i = fInv.length - 1; i >= 0; i--) {
invFactorial.add(fInv[i]);
}
}
return invFactorial.get(n);
}
public long ncr(int n, int r) {
ASSERT(n >= 0);
if (r < 0 || n < r)
return 0;
return mult(fact(n), mult(fInv(r), fInv(n - r)));
}
public long normalize(long x) {
x %= modulus();
if (x < 0)
x += modulus();
return x;
}
public long add(long a, long b) {
long v = a + b;
return v < modulus() ? v : v - modulus();
}
public long subtract(long a, long b) {
long v = a - b;
return v < 0 ? v + modulus() : v;
}
public long mult(long a, long b) {
return (a * b) % modulus();
}
public long pow(long x, int e) {
if (e < 0) {
x = inv(x);
e *= -1;
}
if (e == 0)
return 1;
if ((e & 1) > 0)
return mult(x, pow(x, e - 1));
return pow(mult(x, x), e / 2);
}
public long inv(long value) {
long g = modulus(), x = 0, y = 1;
for (long r = value; r != 0; ) {
long q = g / r;
g %= r;
long temp = g;
g = r;
r = temp;
x -= q * y;
temp = x;
x = y;
y = temp;
}
ASSERT(g == 1);
ASSERT(y == modulus() || y == -modulus());
return normalize(x);
}
}
public static class Mod107 extends NumberTheory.Modulus<NumberTheory.Mod107> {
public long modulus() {
return 1_000_000_007L;
}
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
5f773776605d16f33f91b812f2578fa5
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 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.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
private static final NumberTheory.Mod107 mod = new NumberTheory.Mod107();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long T = in.nextLong();
int[] t = in.readIntArray(n);
long[] cumT = new long[n + 1];
int min = -1, max = -1;
for (int i = 0; i < n; i++) {
cumT[i + 1] = cumT[i] + t[i];
if (min == -1 && cumT[i + 1] + (i + 1) > T)
min = i;
if (max == -1 && cumT[i + 1] > T)
max = i;
}
if (min == -1)
min = 0;
if (max == -1)
max = n;
long[] invPow2 = new long[max + 2 - min];
long inv2 = mod.inv(2);
invPow2[0] = mod.pow(inv2, min);
for (int i = 0; i + 1 < invPow2.length; i++) {
invPow2[i + 1] = mod.mult(invPow2[i], inv2);
}
long answer = min - 1;
int mostBad = min;
long pr = 0;
for (int i = 0; i <= mostBad; i++) {
pr = mod.add(pr, mod.ncr(min, i));
}
pr = mod.mult(pr, invPow2[0]);
for (int count = min; count <= max; count++) {
int mostBadTarget = (int) (T - cumT[count]);
long subtract = 0;
while (mostBad > mostBadTarget) {
subtract = mod.add(subtract, mod.ncr(count, mostBad));
mostBad--;
}
pr = mod.subtract(pr, mod.mult(subtract, invPow2[count - min]));
answer = mod.add(answer, pr);
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count + 1 - min]));
}
out.println(answer);
}
}
static class InputReader {
public final BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
static class NumberTheory {
private static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
final IntStack factorial = new IntStack();
final IntStack invFactorial = new IntStack();
public abstract long modulus();
public Modulus() {
super();
factorial.push(1);
invFactorial.push(1);
}
public long fact(int n) {
while (factorial.size() <= n) {
factorial.push((int) mult(factorial.get(factorial.size() - 1), factorial.size()));
}
return factorial.get(n);
}
public long fInv(int n) {
int lastKnown = invFactorial.size() - 1;
if (lastKnown < n) {
long[] fInv = new long[n - lastKnown];
fInv[0] = inv(fact(n));
for (int i = 1; i < fInv.length; i++) {
fInv[i] = mult(fInv[i - 1], n - i + 1);
}
for (int i = fInv.length - 1; i >= 0; i--) {
invFactorial.push((int) fInv[i]);
}
}
return invFactorial.get(n);
}
public long ncr(int n, int r) {
ASSERT(n >= 0);
if (r < 0 || n < r)
return 0;
return mult(fact(n), mult(fInv(r), fInv(n - r)));
}
public long normalize(long x) {
x %= modulus();
if (x < 0)
x += modulus();
return x;
}
public long add(long a, long b) {
long v = a + b;
return v < modulus() ? v : v - modulus();
}
public long subtract(long a, long b) {
long v = a - b;
return v < 0 ? v + modulus() : v;
}
public long mult(long a, long b) {
return (a * b) % modulus();
}
public long pow(long x, int e) {
if (e < 0) {
x = inv(x);
e *= -1;
}
if (e == 0)
return 1;
if ((e & 1) > 0)
return mult(x, pow(x, e - 1));
return pow(mult(x, x), e / 2);
}
public long inv(long value) {
long g = modulus(), x = 0, y = 1;
for (long r = value; r != 0; ) {
long q = g / r;
g %= r;
long temp = g;
g = r;
r = temp;
x -= q * y;
temp = x;
x = y;
y = temp;
}
ASSERT(g == 1);
ASSERT(y == modulus() || y == -modulus());
return normalize(x);
}
}
public static class Mod107 extends NumberTheory.Modulus<NumberTheory.Mod107> {
public long modulus() {
return 1_000_000_007L;
}
}
}
static class Util {
public static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
private Util() {
}
}
static class IntStack {
int[] array;
int size = 0;
public IntStack() {
this(8);
}
public IntStack(int capacity) {
array = new int[capacity];
}
public void push(int item) {
if (size >= array.length)
array = resize(array);
array[size++] = item;
}
public int size() {
return size;
}
public int get(int i) {
Util.ASSERT(i < size);
return array[i];
}
private static int[] resize(int[] array) {
int[] newArray = new int[array.length << 1];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public String toString() {
int[] trimmed = new int[size];
System.arraycopy(array, 0, trimmed, 0, size);
return Arrays.toString(trimmed);
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
f655cd4c3106381590e4a68126bbcbb6
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.function.IntPredicate;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
private static final NumberTheory.Mod107 mod = new NumberTheory.Mod107();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long T = in.nextLong();
int[] t = in.readIntArray(n);
long[] cumT = new long[n + 1];
for (int i = 0; i < n; i++) {
cumT[i + 1] = cumT[i] + t[i];
}
int min = -1 + BinarySearch.binarySearch(count -> {
if (count < 0)
return false;
if (count > n)
return true;
return cumT[count] + count > T;
});
int max = -1 + BinarySearch.binarySearch(count -> {
if (count < 0)
return false;
if (count > n)
return true;
return cumT[count] > T;
});
long[] invPow2 = new long[max + 2 - min];
long inv2 = mod.inv(2);
invPow2[0] = mod.pow(inv2, min);
for (int i = 0; i + 1 < invPow2.length; i++) {
invPow2[i + 1] = mod.mult(invPow2[i], inv2);
}
long answer = min - 1;
int mostBad = min;
long pr = 0;
for (int i = 0; i <= mostBad; i++) {
pr = mod.add(pr, mod.mult(mod.ncr(min, i), invPow2[0]));
}
for (int count = min; count <= max; count++) {
int mostBadTarget = (int) (T - cumT[count]);
while (mostBad > mostBadTarget) {
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count - min]));
mostBad--;
}
answer = mod.add(answer, pr);
pr = mod.subtract(pr, mod.mult(mod.ncr(count, mostBad), invPow2[count + 1 - min]));
}
out.println(answer);
}
}
static class InputReader {
public final BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
static class NumberTheory {
private static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
final ArrayList<Long> factorial = new ArrayList<>();
final ArrayList<Long> invFactorial = new ArrayList<>();
public abstract long modulus();
public Modulus() {
super();
factorial.add(1L);
invFactorial.add(1L);
}
public long fact(int n) {
while (factorial.size() <= n) {
factorial.add(mult(factorial.get(factorial.size() - 1), factorial.size()));
}
return factorial.get(n);
}
public long fInv(int n) {
int lastKnown = invFactorial.size() - 1;
if (lastKnown < n) {
long[] fInv = new long[n - lastKnown];
fInv[0] = inv(fact(n));
for (int i = 1; i < fInv.length; i++) {
fInv[i] = mult(fInv[i - 1], n - i + 1);
}
for (int i = fInv.length - 1; i >= 0; i--) {
invFactorial.add(fInv[i]);
}
}
return invFactorial.get(n);
}
public long ncr(int n, int r) {
ASSERT(n >= 0);
if (r < 0 || n < r)
return 0;
return mult(fact(n), mult(fInv(r), fInv(n - r)));
}
public long normalize(long x) {
x %= modulus();
if (x < 0)
x += modulus();
return x;
}
public long add(long a, long b) {
long v = a + b;
return v < modulus() ? v : v - modulus();
}
public long subtract(long a, long b) {
long v = a - b;
return v < 0 ? v + modulus() : v;
}
public long mult(long a, long b) {
return (a * b) % modulus();
}
public long pow(long x, int e) {
if (e < 0) {
x = inv(x);
e *= -1;
}
if (e == 0)
return 1;
if ((e & 1) > 0)
return mult(x, pow(x, e - 1));
return pow(mult(x, x), e / 2);
}
public long inv(long value) {
long g = modulus(), x = 0, y = 1;
for (long r = value; r != 0; ) {
long q = g / r;
g %= r;
long temp = g;
g = r;
r = temp;
x -= q * y;
temp = x;
x = y;
y = temp;
}
ASSERT(g == 1);
ASSERT(y == modulus() || y == -modulus());
return normalize(x);
}
}
public static class Mod107 extends NumberTheory.Modulus<NumberTheory.Mod107> {
public long modulus() {
return 1_000_000_007L;
}
}
}
static class BinarySearch {
public static int binarySearch(IntPredicate bigEnough) {
int tooSmall = 0, tooBig;
if (bigEnough.test(tooSmall)) {
return tooSmall;
}
for (tooBig = 1; !bigEnough.test(tooBig); tooBig *= 2)
;
if (!bigEnough.test(tooBig - 1)) {
return tooBig;
}
while (tooBig - tooSmall > 1) {
int center = tooSmall + (tooBig - tooSmall) / 2;
if (!bigEnough.test(center)) {
tooSmall = center;
} else {
tooBig = center;
}
}
return tooBig;
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
26ed5740d7d205cfceb9aac81e858a27
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.function.IntPredicate;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FCrosswordExpert solver = new FCrosswordExpert();
solver.solve(1, in, out);
out.close();
}
static class FCrosswordExpert {
private static final NumberTheory.Mod107 mod = new NumberTheory.Mod107();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long T = in.nextLong();
int[] t = in.readIntArray(n);
long[] cumT = new long[n + 1];
for (int i = 0; i < n; i++) {
cumT[i + 1] = cumT[i] + t[i];
}
int min = -1 + BinarySearch.binarySearch(count -> {
if (count < 0)
return false;
if (count > n)
return true;
return cumT[count] + count > T;
});
int max = -1 + BinarySearch.binarySearch(count -> {
if (count < 0)
return false;
if (count > n)
return true;
return cumT[count] > T;
});
long answer = min - 1;
int mostBad = min;
long pr = 0;
for (int i = 0; i <= mostBad; i++) {
pr = mod.add(pr, mod.div(mod.ncr(min, i), mod.pow(2, min)));
}
for (int count = min; count <= max; count++) {
int mostBadTarget = (int) (T - cumT[count]);
while (mostBad > mostBadTarget) {
pr = mod.subtract(pr, mod.div(mod.ncr(count, mostBad), mod.pow(2, count)));
mostBad--;
}
answer = mod.add(answer, pr);
pr = mod.subtract(pr, mod.div(mod.ncr(count, mostBad), mod.pow(2, count + 1)));
}
out.println(answer);
}
}
static class InputReader {
public final BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
static class NumberTheory {
private static void ASSERT(boolean assertion) {
if (!assertion)
throw new AssertionError();
}
public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
final ArrayList<Long> factorial = new ArrayList<>();
final ArrayList<Long> invFactorial = new ArrayList<>();
public abstract long modulus();
public Modulus() {
super();
factorial.add(1L);
invFactorial.add(1L);
}
public long fact(int n) {
while (factorial.size() <= n) {
factorial.add(mult(factorial.get(factorial.size() - 1), factorial.size()));
}
return factorial.get(n);
}
public long fInv(int n) {
int lastKnown = invFactorial.size() - 1;
if (lastKnown < n) {
long[] fInv = new long[n - lastKnown];
fInv[0] = inv(fact(n));
for (int i = 1; i < fInv.length; i++) {
fInv[i] = mult(fInv[i - 1], n - i + 1);
}
for (int i = fInv.length - 1; i >= 0; i--) {
invFactorial.add(fInv[i]);
}
}
return invFactorial.get(n);
}
public long ncr(int n, int r) {
ASSERT(n >= 0);
if (r < 0 || n < r)
return 0;
return mult(fact(n), mult(fInv(r), fInv(n - r)));
}
public long normalize(long x) {
x %= modulus();
if (x < 0)
x += modulus();
return x;
}
public long add(long a, long b) {
long v = a + b;
return v < modulus() ? v : v - modulus();
}
public long subtract(long a, long b) {
long v = a - b;
return v < 0 ? v + modulus() : v;
}
public long mult(long a, long b) {
return (a * b) % modulus();
}
public long div(long a, long b) {
return mult(a, inv(b));
}
public long pow(long x, int e) {
if (e < 0) {
x = inv(x);
e *= -1;
}
if (e == 0)
return 1;
if ((e & 1) > 0)
return mult(x, pow(x, e - 1));
return pow(mult(x, x), e / 2);
}
public long inv(long value) {
long g = modulus(), x = 0, y = 1;
for (long r = value; r != 0; ) {
long q = g / r;
g %= r;
long temp = g;
g = r;
r = temp;
x -= q * y;
temp = x;
x = y;
y = temp;
}
ASSERT(g == 1);
ASSERT(y == modulus() || y == -modulus());
return normalize(x);
}
}
public static class Mod107 extends NumberTheory.Modulus<NumberTheory.Mod107> {
public long modulus() {
return 1_000_000_007L;
}
}
}
static class BinarySearch {
public static int binarySearch(IntPredicate bigEnough) {
int tooSmall = 0, tooBig;
if (bigEnough.test(tooSmall)) {
return tooSmall;
}
for (tooBig = 1; !bigEnough.test(tooBig); tooBig *= 2)
;
if (!bigEnough.test(tooBig - 1)) {
return tooBig;
}
while (tooBig - tooSmall > 1) {
int center = tooSmall + (tooBig - tooSmall) / 2;
if (!bigEnough.test(center)) {
tooSmall = center;
} else {
tooBig = center;
}
}
return tooBig;
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
d23d37613ccefbafa5630dcc9de7549e
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
//package educational.round68;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
long T = nl();
int[] a = na(n);
long[] high = new long[n+1];
for(int i = 0;i <= n;i++){
high[i] = T;
if(i < n){
T -= a[i];
}
}
// C(i, [T-i, T])
long[] H = go(high);
long m = 1;
long E = 0;
long pnum = 0;
int mod = 1000000007;
for(int i = n;i >= 0;i--){
long num = (H[i]) * m % mod;
E += (num-pnum) % mod * i % mod;
pnum = num;
m = m * 2 % mod;
}
E %= mod;
if(E < 0)E += mod;
out.println(E* pow(invl(2, mod), n, mod) % mod);
}
// sum_{j<=h[i]} C(i, j)
// h[i] is decremental
long[] go(long[] h)
{
long s = 1;
long[] ret = new long[h.length];
int tail = 0;
for(int i = 0;i < h.length;i++){
if(h[i] < 0)break;
if(i > 0){
s = s * 2;
s += C(i-1, tail+1, mod, fif);
s %= mod;
tail++;
while(tail > h[i]){
s -= C(i, tail, mod, fif);
tail--;
}
s %= mod;
if(s < 0)s += mod;
}
ret[i] = s;
}
return ret;
}
int mod = 1000000007;
int[][] fif = enumFIF(400005, mod);
public static long C(int n, int r, int mod, int[][] fif) {
if (n < 0 || r < 0 || r > n)
return 0;
return (long) fif[0][n] * fif[1][r] % mod * fif[1][n - r] % mod;
}
public static int[][] enumFIF(int n, int mod) {
int[] f = new int[n + 1];
int[] invf = new int[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = (int) ((long) f[i - 1] * i % mod);
}
long a = f[n];
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
invf[n] = (int) (p < 0 ? p + mod : p);
for (int i = n - 1; i >= 0; i--) {
invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod);
}
return new int[][] { f, invf };
}
public static long pow(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0)
ret = ret * a % mod;
}
return ret;
}
public static long invl(long a, long mod) {
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
return p < 0 ? p + mod : p;
}
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
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
c319e23641b9bf02cebcd8b34dcc7e4e
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
//package ContestEd68;
import java.io.*;
import java.util.StringTokenizer;
public class mainF {
public static PrintWriter out = new PrintWriter(System.out);
public static FastScanner enter = new FastScanner(System.in);
public static long fact[];
public static long mod = (long) (1e9) + 7;
public static long dub = bin_pow(2, mod - 2, mod);
public static void main(String[] args) throws IOException {
int n = enter.nextInt();
long T = enter.nextLong();
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = fact[i - 1] * i;
fact[i] %= mod;
}
long t[] = new long[n + 1];
for (int i = 1; i <= n; i++) {
t[i] = enter.nextLong();
}
for (int i = 1; i < n + 1; i++) {
t[i] += t[i - 1];
}
for (int i = 1; i < n + 1; i++) {
t[i] = T - t[i];
}
int c = 1;
while (c < t.length && t[c] >= c) c++;
if (c == t.length) {
System.out.println(n);
return;
}
long[] mass = new long[n + 1];
for (int i = 0; i <= t[c]; i++) {
mass[c] += cnk(c, i);
mass[c] %= mod;
}
for (int i = c + 1; i < n + 1; i++) {
if (t[i] < 0) break;
long tmp = mass[i - 1] * 2 + cnk(i-1 , (int) t[i - 1]+1);
tmp %= mod;
int up = (int) t[i-1]+1;
while (up != t[i]) {
tmp -= cnk(i, up);
up--;
tmp %= mod;
}
mass[i] = tmp;
}
long ans = 0;
for (int i = 1; i < n + 1; i++) {
if (t[i] < 0) break;
if (t[i] >= i) {
ans++;
continue;
}
ans += mass[i] * bin_pow(dub, i, mod);
ans %= mod;
}
ans = (ans % mod + mod) % mod;
System.out.println(ans);
}
public static long cnk(int n, int k) {
long ans = fact[n];
long tmp = fact[n - k] * fact[k];
tmp %= mod;
tmp = bin_pow(tmp, mod - 2, mod);
ans *= tmp;
ans %= mod;
return ans;
}
public static long bin_pow(long a, long b, long mod) {//a^b %mod
long ans = 1;
while (b != 0) {
if ((b & 1) == 1) ans *= a;
a *= a;
ans %= mod;
a %= mod;
b >>= 1;
}
return ans;
}
static class FastScanner {
BufferedReader br;
StringTokenizer stok;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
cac51284a47d7527159d37105b4c02ea
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class F implements Runnable {
public static void main (String[] args) {new Thread(null, new F(), "_cf", 1 << 28).start();}
long MOD = (long)1e9+7;
int MOD2 = 500000004;
int MAX = 200200;
long[] fact, inv, invFact;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
fact = new long[MAX];
inv = new long[MAX];
inv[1] = 1; inv[0] = 1;
for (int i = 2; i < inv.length; ++i) {
long p1 = (MOD - (MOD/i));
long p2 = inv[(int)(MOD%i)];
inv[i] = p1 * p2 % MOD;
}
invFact = new long[MAX];
fact[0] = invFact[0] = 1;
for(int i = 1; i < MAX; i++) {
fact[i] = fact[i-1] * i % MOD;
invFact[i] = invFact[i-1] * inv[i] % MOD;
}
int n = fs.nextInt();
long T = fs.nextLong();
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = fs.nextLong();
long[] lims = new long[n];
long[] sums = new long[n];
long[] invSums = new long[n];
long[] pow2s = new long[n];
long pref = 0;
for(int i = 0; i < n; i++) {
pref += a[i];
long two = Math.max(0, T - pref);
lims[i] = Math.min(two, i+1);
}
int curRow = 1, curCol = 0;
long sum = 0, pow2 = 1;
for(int i = 0; i < n; i++) {
pow2 = mult(pow2, 2);
pow2s[i] = pow2;
if(i == 0) {
while(curCol <= lims[i]) {
sum = add(sum, nChooseK(curRow, curCol++));
}
sums[i] = sum;
invSums[i] = sub(pow2, sums[i]);
sum = add(nChooseK(curRow, curCol), mult(2, sum));
curCol++;
curRow++;
}
else {
if(curCol <= lims[i]) {
while(curCol <= lims[i]) {
sum = add(sum, nChooseK(curRow, curCol++));
}
}
else if(curCol-1 > lims[i]) {
while(curCol-1 > lims[i]) {
sum = sub(sum, nChooseK(curRow, curCol-1));
curCol--;
}
}
sums[i] = sum;
invSums[i] = sub(pow2, sums[i]);
sum = add(nChooseK(curRow, curCol), mult(2, sum));
curRow++; curCol++;
}
}
pref = 0;
long pref2 = 0;
for(int i = 0; i < n; i++) {
pref += a[i]+1;
pref2 += a[i];
if(pref <= T) {
sums[i] = pow2s[i]; invSums[i] = 0;
}
else if(pref2 > T) {
sums[i] = 0; invSums[i] = pow2s[i];
}
}
long[] pow2Invs = new long[n];
pow2Invs[0] = MOD2;
for(int i = 1; i < n; i++) {
pow2Invs[i] = mult(pow2Invs[i-1], MOD2);
}
// System.out.println(Arrays.toString(sums));
// System.out.println(Arrays.toString(invSums));
// System.out.println();
for(int i = 0; i < n; i++) {
sums[i] = mult(sums[i], pow2Invs[i]);
invSums[i] = mult(invSums[i], pow2Invs[i]);
}
long res = 0;
for(int i = 0; i < n; i++) {
res = add(res, sums[i]);
}
out.println(res);
// System.out.println(Arrays.toString(sums));
// System.out.println(Arrays.toString(invSums));
out.close();
}
long nChooseK(int n, int k) {
if(k > n) return 0;
long num = fact[n];
long den = invFact[k] * invFact[n-k] % MOD;
return num * den % MOD;
}
long sub(long a, long b) {
a -= b;
if(a < 0) a += MOD;
return a;
}
long mult(long a, long b) {
return (a * b) % MOD;
}
long add(long a, long b) {
a += b;
a %= MOD;
return a;
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
26f0a547a8cd0f6084f7d542c916a8f2
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fcking interest
*******************************
I'm standing on top of my Monopoly board
That means I'm on top of my game and it don't stop
til my hip don't hop anymore
https://www.a2oj.com/Ladder16.html
*******************************
Shining through the city with a little funk and soul
*******************************
300iq as writer = Sad!
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1194F
{
static long MOD = 1000000007L;
public static void main(String hi[]) throws Exception
{
long inv2 = power(2, MOD-2, MOD);
fac = new long[200001];
invfac = new long[200001];
fac[0] = invfac[0] = 1L;
for(int i=1; i <= 200000; i++)
fac[i] = (fac[i-1]*i)%MOD;
invfac[200000] = power(fac[200000], MOD-2, MOD);
for(int i=199999; i >= 1; i--)
invfac[i] = (invfac[i+1]*(i+1))%MOD;
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
long T = Long.parseLong(st.nextToken());
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken())+1;
long res = 0L;
long sum = 0L;
long denom = 1L;
int dex = 0;
while(dex < N && sum+arr[dex] <= T)
{
sum += arr[dex++];
denom = (denom*inv2)%MOD;
}
for(int ones=0; ones <= dex; ones++)
{
long temp = (comb(dex, ones)*denom)%MOD;
long addend = (temp*dex)%MOD;
if(dex < N && sum+arr[dex]-1 == T)
addend = (addend*inv2)%MOD;
res += addend;
if(res >= MOD)
res -= MOD;
sum--;
if(dex < N && sum+arr[dex] <= T)
{
sum += arr[dex++];
denom = (denom*inv2)%MOD;
}
}
System.out.println(res%MOD);
}
static long[] fac, invfac;
public static long comb(int a, int b)
{
long res = (fac[a]*invfac[b])%MOD;
return (res*invfac[a-b])%MOD;
}
public static long power(long x, long y, long p)
{
//0^0 = 1
long res = 1L;
x = x%p;
while(y > 0)
{
if((y&1)==1)
res = (res*x)%p;
y >>= 1;
x = (x*x)%p;
}
return res;
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
98b60e39d060eba779baacd04ca3f31c
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rustam Musin (t.me/musin_acm)
*/
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);
FEkspertPoKrossvordam solver = new FEkspertPoKrossvordam();
solver.solve(1, in, out);
out.close();
}
static class FEkspertPoKrossvordam {
int mod = (int) 1e9 + 7;
int[] fact;
int[] pow2;
int[] pow2inv;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
long t = in.readLong();
init(n);
int curSum = 1;
int curK = 0;
int res = 0;
long prevt = 0;
for (int i = 0; i < n; i++) {
curSum = add(mul(curSum, 2), c(i, ++curK));
prevt += in.readInt();
if (prevt > t) {
break;
}
int possibleFails = (int) Math.min(i + 1, t - prevt);
while (curK < possibleFails) {
curSum = add(curSum, c(i + 1, ++curK));
}
while (curK > possibleFails) {
curSum = sub(curSum, c(i + 1, curK--));
}
res = add(res, mul(curSum, pow2inv[i + 1])); //sumc (1, ...)
}
out.print(res);
}
int add(int a, int b) {
a += b;
if (a >= mod) {
a -= mod;
}
return a;
}
int sub(int a, int b) {
a -= b;
if (a < 0) {
a += mod;
}
return a;
}
int mul(int a, int b) {
long c = a * (long) b;
return (int) (c % mod);
}
int pow(int x, int p) {
if (p == 0) {
return 1;
}
int res = pow(x, p / 2);
res = mul(res, res);
if (p % 2 == 1) {
res = mul(res, x);
}
return res;
}
int inv(int x) {
return pow(x, mod - 2);
}
int div(int a, int b) {
return mul(a, inv(b));
}
void init(int n) {
fact = new int[n + 1];
pow2 = new int[n + 1];
pow2inv = new int[n + 1];
fact[0] = pow2[0] = pow2inv[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = mul(fact[i - 1], i);
pow2[i] = mul(pow2[i - 1], 2);
pow2inv[i] = inv(pow2[i]);
}
}
int c(int n, int k) {
if (k > n) {
return 0;
}
return div(fact[n], mul(fact[k], fact[n - k]));
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
d12517d88a58f6244ba9416c6fa2cf53
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rustam Musin (t.me/musin_acm)
*/
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);
FEkspertPoKrossvordam solver = new FEkspertPoKrossvordam();
solver.solve(1, in, out);
out.close();
}
static class FEkspertPoKrossvordam {
int mod = (int) 1e9 + 7;
int[] fact;
int[] inv;
int[] factInv;
int[] pow2inv;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
long t = in.readLong();
init(Math.max(n, 2));
int curSum = 1;
int curK = 0;
int res = 0;
long prevt = 0;
for (int i = 0; i < n; i++) {
curSum = add(mul(curSum, 2), c(i, ++curK));
prevt += in.readInt();
if (prevt > t) {
break;
}
int possibleFails = (int) Math.min(i + 1, t - prevt);
while (curK < possibleFails) {
curSum = add(curSum, c(i + 1, ++curK));
}
while (curK > possibleFails) {
curSum = sub(curSum, c(i + 1, curK--));
}
res = add(res, mul(curSum, pow2inv[i + 1])); //sumc (1, ...)
}
out.print(res);
}
int add(int a, int b) {
a += b;
if (a >= mod) {
a -= mod;
}
return a;
}
int sub(int a, int b) {
a -= b;
if (a < 0) {
a += mod;
}
return a;
}
int mul(int a, int b) {
long c = a * (long) b;
return (int) (c % mod);
}
void init(int n) {
fact = new int[n + 1];
inv = new int[n + 1];
factInv = new int[n + 1];
pow2inv = new int[n + 1];
fact[0] = inv[0] = factInv[0] = pow2inv[0] = 1;
fact[1] = inv[1] = 1;
for (int i = 2; i <= n; i++) {
fact[i] = mul(fact[i - 1], i);
inv[i] = mul(-mod / i + mod, inv[mod % i]);
}
for (int i = 1; i <= n; i++) {
factInv[i] = mul(factInv[i - 1], inv[i]);
pow2inv[i] = mul(pow2inv[i - 1], inv[2]);
}
}
int c(int n, int k) {
if (k > n) {
return 0;
}
return mul(fact[n], mul(factInv[k], factInv[n - k]));
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
691786a106cad560763ea91109ee9387
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rustam Musin (t.me/musin_acm)
*/
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);
FEkspertPoKrossvordam solver = new FEkspertPoKrossvordam();
solver.solve(1, in, out);
out.close();
}
static class FEkspertPoKrossvordam {
int mod = (int) 1e9 + 7;
int[] fact;
int[] inv;
int[] factInv;
int[] pow2inv;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
long t = in.readLong();
init(Math.max(n, 2));
int curSum = 1;
int curK = 0;
int res = 0;
long prevt = 0;
for (int i = 0; i < n; i++) {
curSum = add(mul(curSum, 2), c(i, ++curK));
prevt += in.readInt();
if (prevt > t) {
break;
}
int possibleFails = (int) Math.min(i + 1, t - prevt);
while (curK < possibleFails) {
curSum = add(curSum, c(i + 1, ++curK));
}
while (curK > possibleFails) {
curSum = sub(curSum, c(i + 1, curK--));
}
res = add(res, mul(curSum, pow2inv[i + 1])); //sumc (1, ...)
}
out.print(res);
}
int add(int a, int b) {
a += b;
if (a >= mod) {
a -= mod;
}
return a;
}
int sub(int a, int b) {
a -= b;
if (a < 0) {
a += mod;
}
return a;
}
int mul(int a, int b) {
long c = a * (long) b;
return (int) (c % mod);
}
int norm(int x) {
x %= mod;
x += mod;
x %= mod;
return x;
}
void init(int n) {
fact = new int[n + 1];
inv = new int[n + 1];
factInv = new int[n + 1];
pow2inv = new int[n + 1];
fact[0] = inv[0] = factInv[0] = pow2inv[0] = 1;
fact[1] = inv[1] = 1;
for (int i = 2; i <= n; i++) {
fact[i] = mul(fact[i - 1], i);
inv[i] = norm(mul(-mod / i, inv[mod % i]));
}
for (int i = 1; i <= n; i++) {
factInv[i] = mul(factInv[i - 1], inv[i]);
pow2inv[i] = mul(pow2inv[i - 1], inv[2]);
}
}
int c(int n, int k) {
if (k > n) {
return 0;
}
return mul(fact[n], mul(factInv[k], factInv[n - k]));
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
5cbca80494963e5c76759fd088909644
|
train_001.jsonl
|
1563115500
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q > 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
256 megabytes
|
import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
public static void main(String[] args) throws Exception {
new template().run();
}
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = f.nextInt(); long t = f.nextLong();
long[] arr = new long[n];
long[] fact = new long[n+1], inv = new long[n+1];
fact[0] = inv[0] = 1;
int[] cnt = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = f.nextLong();
fact[i+1] = fact[i] * (i+1) % MOD;
inv[i+1] = modInv(fact[i+1]);
if(i != 0) arr[i] += arr[i-1];
cnt[i] = (int) Math.min(t-arr[i], i+1);
}
long ans = 0;
long psum = 1;
int pcnt = 0;
long cur = 500000004;
for(int i = 0; i < n; i++) {
if(cnt[i] < 0) break;
while(pcnt < cnt[i]) {
pcnt++;
psum = (psum + fact[i+1]*inv[pcnt]%MOD*inv[i+1-pcnt]%MOD)%MOD;
}
while(pcnt > cnt[i]) {
psum = (psum - fact[i+1]*inv[pcnt]%MOD*inv[i+1-pcnt]%MOD+MOD)%MOD;
pcnt--;
}
ans = (ans + cur * psum) % MOD;
cur = cur * 500000004 % MOD;
psum = psum * 2 % MOD;
pcnt++;
if(cnt[i] != i+1) psum = (psum + fact[i+1]*inv[pcnt]%MOD*inv[i+1-pcnt]%MOD) % MOD;
}
out.println(ans);
///
out.flush();
}
long MOD = 1000000007, x, y;
public long modInv(long a) {
gcd(a, MOD);
return (x%MOD+MOD)%MOD;
}
public void gcd(long a, long b) {
if(a == 0) {
x = 0; y = 1;
return;
}
gcd(b%a,a);
long nx = y - b/a*x;
long ny = x;
x = nx;
y = ny;
return;
}
///
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
Java
|
["3 5\n2 2 2", "3 5\n2 1 2"]
|
2 seconds
|
["750000007", "125000003"]
|
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
|
Java 8
|
standard input
|
[
"dp",
"combinatorics",
"two pointers",
"number theory",
"probabilities"
] |
a44cba5685500b16e24b8fba30451bc5
|
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
| 2,400 |
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
|
standard output
| |
PASSED
|
6a79c37ba4fe8f3ac2694e7b035025d1
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.util.Map.*;
/**
* 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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int INF = Integer.MAX_VALUE;
final int TYPE = 0;
final int TIME = 1;
final int VALUE = 2;
HashMap<Integer, TreeMap<Integer,Integer>> addRanks;
HashMap<Integer, TreeMap<Integer,Integer>> remRanks;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[][] queries = new int[n][3];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
queries[i][TYPE] = in.nextInt();
queries[i][TIME] = in.nextInt();
queries[i][VALUE] = in.nextInt();
}
addRanks = buildRank(queries, 1);
remRanks = buildRank(queries, 2);
HashMap<Integer, Integer[]> addMap = new HashMap<>();
HashMap<Integer, Integer[]> remMap = new HashMap<>();
for (int i = 0; i < n; i++) {
if (queries[i][TYPE] == 1) {
addItemToMap(addMap, queries[i][TIME], queries[i][VALUE],queries[i][TYPE]);
} else if (queries[i][TYPE] == 2) {
addItemToMap(remMap, queries[i][TIME], queries[i][VALUE],queries[i][TYPE]);
} else {
//sb.append(queries[i][TYPE]);
sb.append(countNoValue(addMap, remMap, queries[i][TIME], queries[i][VALUE]));
sb.append("\n");
}
}
out.print(sb);
}
private void update(Integer[] arrs, int i){
for(; i < arrs.length; i += (-i & i)){
arrs[i]++;
}
}
private int get(Integer[] arrs, int l, int r){
return get(arrs, r) - get(arrs, l - 1);
}
private int get(Integer[] arrs, int i){
int ans = 0;
for(; i > 0; i -= (-i & i)){
ans += arrs[i];
}
return ans;
}
private HashMap<Integer, TreeMap<Integer,Integer>> buildRank(int[][] queries,int type){
HashMap<Integer, TreeMap<Integer,Integer>> ranks = new HashMap<>();
HashMap<Integer, ArrayList<Integer>> maps = new HashMap<>();
int n = queries.length;
for(int i = 0; i < n; ++i){
if(queries[i][TYPE] == type){
ArrayList<Integer> lst = maps.get(queries[i][VALUE]);
if(lst == null){
lst = new ArrayList<Integer>();
}
lst.add(queries[i][TIME]);
maps.put(queries[i][VALUE],lst);
}
}
for(Entry<Integer,ArrayList<Integer>> entry : maps.entrySet()){
int key = entry.getKey();
ArrayList<Integer> lst = entry.getValue();
Collections.sort(lst);
TreeMap<Integer,Integer> rank = ranks.get(key);
if(rank == null){
rank = new TreeMap<>();
}
int rankId = 1;
rank.put(lst.get(0), rankId++);
for(int i = 1; i < lst.size(); ++i){
if(lst.get(i) != lst.get(i - 1)){
rank.put(lst.get(i), rankId++);
}
}
ranks.put(key, rank);
}
return ranks;
}
private int countNoValue(HashMap<Integer, Integer[]> addMap, HashMap<Integer,Integer[]> remMap, int time, int value) {
TreeMap<Integer,Integer> addRank = addRanks.get(value);
TreeMap<Integer,Integer> remRank = remRanks.get(value);
int ans = 0;
Integer[] times = addMap.get(value);
if (times == null) {
return 0;
}
//count added Item
Integer id = addRank.lowerKey(time + 1);
if(id == null) return 0;
ans = get(times,addRank.get(id));
//count removed Item
times = remMap.get(value);
if (times != null) {
id = remRank.lowerKey(time + 1);
if(id != null) ans -= get(times,remRank.get(id));
}
return ans;
}
private void addItemToMap(HashMap<Integer, Integer[]> map, int time, int value, int type) {
Integer[] times = map.get(value);
TreeMap<Integer,Integer> rank;
if(type == 1){
rank = addRanks.get(value);
}else{
rank = remRanks.get(value);
}
if (times == null) {
times = new Integer[rank.size() + 1];
Arrays.fill(times, 0);
}
update(times, rank.get(time));
map.put(value, times);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
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
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
06e521c5bb77e267b7a754332a339667
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class E669 {
public static void main(String[] args) throws IOException {
FS input = new FS(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
int[] as = new int[n], ts = new int[n], xs = new int[n];
for(int i = 0; i<n; i++)
{
as[i] = input.nextInt();
ts[i] = input.nextInt();
xs[i] = input.nextInt();
}
TreeSet<Integer> set = new TreeSet<Integer>();
for(int i = 0; i<n; i++) set.add(ts[i]);
HashMap<Integer, Integer> comp = new HashMap<Integer, Integer>();
int idx = 1;
for(int x : set)
{
comp.put(x, idx++);
}
for(int i = 0; i<n; i++) ts[i] = comp.get(ts[i]);
int[] res = new int[n];
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0; i<n; i++)
{
if(!map.containsKey(xs[i])) map.put(xs[i], new ArrayList<Integer>());
map.get(xs[i]).add(i);
}
BIT bit = new BIT(idx+2);
for(int i = 0; i<n; i++)
{
if(i != map.get(xs[i]).get(0)) continue;
for(int q : map.get(xs[i]))
{
int type = as[q];
if(type == 1)
{
bit.upd(ts[q], 1);
}
else if(type == 2)
{
bit.upd(ts[q], -1);
}
else
{
res[q] = bit.csum(ts[q]);
}
}
for(int q : map.get(xs[i]))
{
int type = as[q];
if(type == 1)
{
bit.upd(ts[q], -1);
}
else if(type == 2)
{
bit.upd(ts[q], 1);
}
}
}
for(int i = 0; i<n; i++)
if(as[i] == 3)
out.println(res[i]);
out.close();
}
static class BIT
{
int[] tree;
int n;
BIT(int n)
{
tree = new int[n+1];
this.n = n;
}
/*
* Increases the value at x by v.
*/
void upd(int x, int v)
{
int i = x;
while(i<=n)
{
tree[i]+=v;
i += (i&-i);
}
}
int csum(int x)
{
int s = 0;
while(x>0)
{
s += tree[x];
x -= (x&-x);
}
return s;
}
}
static class FS {
BufferedReader br;
StringTokenizer st;
FS(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
e26b33b1ef7feb59e3e8e1a7a023daab
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class E {
static class Data {
int[] add;
int[] sub;
int n;
public Data(int n) {
this.n = n;
add = new int[n+1];
sub = new int[n+1];
}
public void query(int type, int time) {
if (type == 1) {
while (time <= n) {
add[time]++;
time += time & -time;
}
} else {
while (time <= n) {
sub[time]++;
time += time & -time;
}
}
}
public int num(int time) {
// O(n log n)!!!
int s1 = 0;
int s2 = 0;
int q = time;
while (q > 0) {
s1 += add[q];
q -= q & -q;
}
while (time > 0) {
s2 += sub[time];
time -= time & -time;
}
return s1 - s2;
}
}
public static void print(Object o) {
System.out.println(o);
}
// debugging
public static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static int nextInt(StringTokenizer st) {
return Integer.parseInt(st.nextToken());
}
public static long nextLong(StringTokenizer st) {
return Long.parseLong(st.nextToken());
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
HashMap<Integer, Data> da = new HashMap<>();
HashMap<Integer, ArrayList<Integer>> count = new HashMap<>();
HashMap<Integer, HashMap<Integer, Integer>> ind = new HashMap<>();
int[][] quer = new int[n][3];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
quer[i][0] = nextInt(st);
quer[i][1] = nextInt(st);
quer[i][2] = nextInt(st);
int type = quer[i][0];
int time = quer[i][1];
int num = quer[i][2];
if (count.get(num) == null) {
count.put(num, new ArrayList<>());
ind.put(num, new HashMap<>());
}
count.get(num).add(quer[i][1]);
}
for (ArrayList<Integer> al : count.values()) {
Collections.sort(al);
}
for (int num : count.keySet()) {
for (int i = 0; i < count.get(num).size(); i++) {
ind.get(num).put(count.get(num).get(i), i+1);
}
}
for (int i = 0; i < n; i++) {
int type = quer[i][0];
int time = quer[i][1];
int num = quer[i][2];
if (da.get(num) == null) {
int size = ind.get(num).size();
da.put(num, new Data(size));
}
if (type <= 2) {
da.get(num).query(type, ind.get(num).get(time));
} else {
print(da.get(num).num(ind.get(num).get(time)));
}
}
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
f2682d974c2253f0ba97b98e19d0c9e0
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class CF669E{
public static int index;
public static void main(String[] args)throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
HashMap<Integer, ArrayList<ArrayList<Integer>> > map = new HashMap<Integer, ArrayList<ArrayList<Integer>>>();
int n = in.nextInt();
for(int i = 0; i < n; i++){
int a = in.nextInt(), t = in.nextInt(), x = in.nextInt();
if(a == 1){
if(!map.containsKey(x)){
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
map.put(x, list);
}
add(map.get(x).get(0), t);
}
else if(a == 2){
add(map.get(x).get(1), t);
// remove(map.get(x).get(0), t);
}
else if(map.containsKey(x)) pw.println(getNum(map.get(x).get(0), t) - getNum(map.get(x).get(1), t));
else pw.println("0");
// System.err.println(a+" "+x+" "+t+" "+map.get(x));
}
pw.close();
}
static void add(ArrayList<Integer> list, int num){
int lo = 0, hi = list.size(), mid = (lo+hi)/2;
int temp = 0;
while(lo < hi){
mid = (lo+hi)/2;
temp = list.get(mid);
if( temp >= num) hi = mid;
else lo = mid+1;
}
list.add(lo, num);
}
static void remove(ArrayList<Integer> list, int num){
int lo = 0, hi = list.size()-1, mid = (lo+hi)/2;
int temp = 0;
while(lo < hi){
mid = (lo+hi)/2;
temp = list.get(mid);
if( temp >= num) hi = mid;
else lo = mid+1;
}
if(list.get(lo) <= num) list.remove(lo);
else list.remove(lo-1);
}
static int getNum(ArrayList<Integer> list, int num){
if(list.size() == 0) return 0;
int lo = 0, hi = list.size()-1, mid = (lo+hi)/2;
int temp = 0;
while(lo < hi){
mid = (lo+hi)/2;
temp = list.get(mid);
if( temp >= num) hi = mid;
else lo = mid+1;
}
if(list.get(lo) <= num) return lo+1;
else return lo;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
return null;
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = null;
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public boolean hasNext(){
try {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
}
catch (Exception e) {
return false;
}
return true;
}
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
b4fba5ff08930901143cfec11effa86c
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
/* / フフ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ム
/ )\⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ Y
(⠀⠀| ( ͡° ͜ʖ ͡°)⠀⌒(⠀ ノ
(⠀ ノ⌒ Y ⌒ヽ-く __/
| _⠀。ノ| ノ。 |/
(⠀ー '_人`ー ノ
⠀|\  ̄ _人'彡ノ
⠀ )\⠀⠀ 。⠀⠀ /
⠀⠀(\⠀ #⠀ /
⠀/⠀⠀⠀/ὣ====================D-
/⠀⠀⠀/⠀ \ \⠀⠀\
( (⠀)⠀⠀⠀⠀ ) ).⠀)
(⠀⠀)⠀⠀⠀⠀⠀( | /
|⠀ /⠀⠀⠀⠀⠀⠀ | /
[_] ⠀⠀⠀⠀⠀[___] */
// Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=1000000000+7;
//Euclidean Algorithm
static long gcd(long A,long B){
return (B==0)?A:gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//Modular Inverse
static long inverse(long x) {
return fastExpo(x,MOD-2);
}
//Prime Number Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Reverse an array
static void reverse(int arr[],int l,int r){
while(l<r) {
int tmp=arr[l];
arr[l++]=arr[r];
arr[r++]=tmp;
}
}
//Print array
static void print1d(int arr[]) {
out.println(Arrays.toString(arr));
}
static void print2d(int arr[][]) {
for(int a[]: arr) out.println(Arrays.toString(a));
}
// Pair
static class pair{
int x,y;
pair(int a,int b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Main function(The main code starts from here)
static int N=100000;
static HashMap<Integer,Integer> bit[]=new HashMap[N+1];
static void add(int idx,int key,int val) {
while(idx<=N) {
bit[idx].merge(key, val, Integer:: sum);
idx+=idx&(-idx);
}
}
static int sum(int idx,int key) {
int sum=0;
while(idx>0) {
sum+=(bit[idx].get(key)==null)?0:bit[idx].get(key);
idx-=idx&(-idx);
}
return sum;
}
public static void main (String[] args) throws java.lang.Exception {
int test;
test=1;
//test=sc.nextInt();
while(test-->0) {
int n=sc.nextInt();
for(int i=0;i<=N;i++) bit[i]=new HashMap<>();
HashMap<Integer,Integer> map=new HashMap<>();
TreeSet<Integer> set=new TreeSet<>();
int queries[][]=new int[n][3];
for(int i=0;i<n;i++) {
queries[i][0]=sc.nextInt();
queries[i][1]=sc.nextInt();
queries[i][2]=sc.nextInt();
set.add(queries[i][1]);
}
int idx=1;
for(Integer x: set) map.put(x,idx++);
for(int q[]: queries) {
if(q[0]==1) {
add(map.get(q[1]),q[2],1);
}
else if(q[0]==2) {
add(map.get(q[1]),q[2],-1);
}
else {
out.println(sum(map.get(q[1]),q[2]));
}
}
}
out.flush();
out.close();
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
364eea369ddd8afce077ed6c83363861
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ELittleArtemAndTimeMachine solver = new ELittleArtemAndTimeMachine();
solver.solve(1, in, out);
out.close();
}
static class ELittleArtemAndTimeMachine {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int N = in.nextInt();
Map<Integer, Fenwick> trees = new HashMap<>();
for (int i = 0; i < N; i++) {
int type = in.nextInt();
int time = in.nextInt();
int where = in.nextInt();
Fenwick fen = trees.get(where);
if (fen == null) {
fen = new Fenwick();
trees.put(where, fen);
}
if (type == 1) {
fen.update(time, 1);
} else if (type == 2) {
fen.update(time, -1);
} else if (type == 3) {
out.println(fen.query(time));
}
}
}
class Fenwick {
Map<Integer, Integer> data = new HashMap<>();
private static final int N = 1_000_000_009;
public void update(int pos, int value) {
for (; pos < N; pos |= pos + 1) {
int curr = data.getOrDefault(pos, 0);
data.put(pos, curr + value);
}
}
public int query(int pos) {
int ret = 0;
for (; pos > 0; pos = (pos & (pos + 1)) - 1) {
int curr = data.getOrDefault(pos, 0);
ret += curr;
}
return ret;
}
}
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
235c9592755662c087426634d11bd4cd
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
//package baobab;
import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) {
EIO io = new EIO();
try {
Esolver solver = new Esolver(io);
} finally {
io.close();
}
}
}
class Esolver {
public Esolver(EIO io) {
solve(io);
}
public void solve(EIO io) {
/* Pack times */
TreeSet<Integer> times = new TreeSet<>();
List<Integer> input = new ArrayList<>(100000);
int n = io.nextInt();
for (int i=0; i<n; i++) {
int type = io.nextInt();
int time = io.nextInt();
int val = io.nextInt();
input.add(type);
input.add(time);
input.add(val);
times.add(time);
}
int nextFreeTime = 0;
HashMap<Integer, Integer> packedTimes = new HashMap<>();
for (Integer time : times) {
packedTimes.put(time, nextFreeTime++);
}
/* The actual job */
SegmentMonster seg = new SegmentMonster(n);
int i = 0;
while (i < input.size()) {
int type = input.get(i++);
int time = input.get(i++);
int val = input.get(i++);
time = packedTimes.get(time);
if (type == 1) {
seg.add(val, time);
} else if (type == 2) {
seg.add(-val, time);
} else {
io.println(seg.queryRange(val, 0, time));
}
}
}
}
/** Lowest level of segment tree is an int array.
* Example: arr[5] = -3 means at (packed time) 5 the number 3 was removed from multiset
* Other levels of the segment tree consist of hashmaps
* otherLevels[ */
class SegmentMonster {
int size;
int[] lowestLevel;
HashMap<Integer, Integer>[] otherLevels;
public SegmentMonster(int numberOfElements) {
size = 2;
while (size < numberOfElements) size *= 2;
lowestLevel = new int[size];
otherLevels = new HashMap[size];
}
public void add(int val, int time) {
lowestLevel[time] = val;
val = Math.abs(val);
int k = (time + size) / 2;
while (k >= 1) {
int updatedPartialSum = get(val, 2*k) + get(val, 2*k + 1);
if (otherLevels[k] == null) otherLevels[k] = new HashMap<>();
otherLevels[k].put(val, updatedPartialSum);
k /= 2;
}
}
public int get(int val, int i) {
if (i >= size) {
i -= size;
if (lowestLevel[i] == val) return 1;
if (lowestLevel[i] == -val) return -1;
return 0;
}
if (otherLevels[i] == null) return 0;
Integer partialSum = otherLevels[i].get(val);
if (partialSum == null) return 0;
return partialSum;
}
public int queryRange(int val, int start, int end) {
start += size;
end += size;
int sum = 0;
while (start <= end) {
if (start%2 == 1) sum += get(val, start++);
if (end%2 == 0) sum += get(val, end--);
start /= 2;
end /= 2;
}
return sum;
}
}
class TimeKeeper {
TreeSet<Long> addTimes;
TreeSet<Long> removeTimes;
public TimeKeeper() {
addTimes = new TreeSet<Long>();
removeTimes = new TreeSet<Long>();
}
public void add(long time) {
addTimes.add(time);
}
public void remove(long time) {
removeTimes.add(time);
}
public long get(long time) {
int adds = addTimes.headSet(time, true).size();
int removes = removeTimes.headSet(time, true).size();
return adds - removes;
}
}
class ElementCounter {
private HashMap<Long, Long> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
long count = 1;
if (elements.containsKey(element)) count += elements.get(element);
elements.put(element, count);
}
public void remove(long element) {
long count = elements.get(element);
count--;
if (count == 0) elements.remove(element);
else elements.put(element, count);
}
public long get(long element) {
if (!elements.containsKey(element)) return 0;
return elements.get(element);
}
public int size() {
return elements.size();
}
}
class EIO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public EIO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
6536b35458e4ee2c459a6a954c1f37d7
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Solve4 {
public static void main(String[] args) {
MyScanner scanner = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int q = scanner.nextInt();
int[][] t = new int[3][q];
int[] res = new int[q];
HashMap<Integer, TreeSet<Integer>> map = new HashMap<Integer, TreeSet<Integer>>();
HashMap<Integer, LinkedList<Integer>> map2 = new HashMap<Integer, LinkedList<Integer>>();
for(int i = 0; i < q; i++) {
int type = t[0][i] = scanner.nextInt();
int time = t[1][i] = scanner.nextInt();
int val = t[2][i] = scanner.nextInt();
if(!map.containsKey(val)) {
map.put(val, new TreeSet<Integer>());
map2.put(val, new LinkedList<Integer>());
}
map.get(val).add(time);
map2.get(val).add(i);
}
for(Integer value : map.keySet()) {
TreeSet<Integer> ts = map.get(value);
HashMap<Integer, Integer> trans = new HashMap<Integer, Integer>();
LinkedList<Integer> queries = map2.get(value);
int ind = 0;
for(Integer j : ts) {
trans.put(j, ind++);
}
Tree tree = new Tree(ind+5);
for(Integer index : queries) {
int type = t[0][index];
int time = 1 + trans.get(t[1][index]);
if(type == 1) {
//System.out.println(time);
tree.update(time, tree.get(time) + 1);
} else if(type == 2) {
tree.update(time, tree.get(time) - 1);
} else {
res[index] = (int)tree.query(0, time+1);
}
}
}
for(int i = 0; i < q; i++) {
if(t[0][i] == 3)
out.println(res[i]);
}
out.close();
}
static class Tree{
int n;
int[] d;
Tree(int nmin) {
for(n = 1; n < nmin; n *= 2);
d = new int[2 * n];
Arrays.fill(d, 0);
}
void update(int i, int x) {
d[n + i] = x;
for(int k = (n + i) / 2; k > 0; k >>= 1)
d[k] = d[k * 2] + d[k * 2 + 1];
}
int get(int i) { return d[n + i]; }
//[l, r)
int query(int l, int r) {
int m = 0;
for(; l != 0 && l + (l&-l) <= r; l += l&-l)
m = m + d[(n + l) / (l&-l)];
for(; l < r; r -= r&-r)
m = m + d[(n + r) / (r&-r) - 1];
return m;
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
541c4c28e976a858718fee0b1e1aa714
|
train_001.jsonl
|
1461515700
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws Exception{
Reader.init(System.in);
PrintWriter out = new PrintWriter(System.out);
Main mm=new Main();
int n=Reader.nextInt();
HashMap<Integer,segment_tree> map=new HashMap<Integer,segment_tree>();
for(int i=0;i<n;i++) {
int q=Reader.nextInt();
int time=Reader.nextInt();
int value=Reader.nextInt();
if(q==1) {
if(map.containsKey(value)==false) {
map.put(value,new segment_tree());
}
map.get(value).update(time, 1);
}
else if(q==2){
if(map.containsKey(value)==false) {
map.put(value,new segment_tree());
}
map.get(value).update(time, -1);
}
else {
if(map.containsKey(value)==false) {
//System.out.println(90);
out.println(0);
}
else {
out.println(map.get(value).query(0, time-1));
}
}
}
out.close();
}
}
class segment_tree{
node root;
int max=(int)((10e9)+5);
class node{
int value;
node left;
node right;
node(){
value=0;
}
}
segment_tree(){
this.root=new node();
}
public void update(int index,int value) {
this.update(root, 0, max, index, value);
}
public int query(int l,int r) {
return this.query(root, 0, max, l, r);
}
public void update(node root,int l,int r,int index,int value) {
if(l==r) {
root.value+=value;
}
else {
if(root.left==null) {
root.left=new node();
}
if(root.right==null) {
root.right=new node();
}
int mid=(l+r)/2;
if(index<=mid) {
this.update(root.left, l, mid, index, value);
}
else {
this.update(root.right, mid+1, r, index, value);
}
root.value=root.left.value+root.right.value;
}
}
public int query(node root,int l,int r,int ql,int qr) {
if(l>qr || r<ql) {
//System.out.println(l+" "+r+" "+0);
return 0;
}
else if(l>=ql && r<=qr) {
//System.out.println(l+" "+r+" "+root.value);
return root.value;
}
else {
int sum=0;
int mid=(l+r)/2;
if(root.left!=null) {
sum+=this.query(root.left, l, mid, ql, qr);
}
if(root.right!=null) {
sum+=this.query(root.right, mid+1, r, ql, qr);
}
//System.out.println(l+" "+r+" "+sum);
return sum;
}
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init() throws IOException {
reader = new BufferedReader(
new FileReader("input.txt"));
tokenizer = new StringTokenizer("");
}
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String nextLine() throws IOException{
return reader.readLine();
}
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
|
Java
|
["6\n1 1 5\n3 5 5\n1 2 5\n3 6 5\n2 3 5\n3 7 5", "3\n1 1 1\n2 2 1\n3 3 1"]
|
2 seconds
|
["1\n2\n1", "0"]
| null |
Java 8
|
standard input
|
[
"data structures"
] |
39d7cf2640284689d074accfca527ecc
|
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
| 2,000 |
For each ask operation output the number of instances of integer being queried at the given moment of time.
|
standard output
| |
PASSED
|
db30f38028a6f5552fe634df0560b633
|
train_001.jsonl
|
1398612600
|
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:A swap operation is the following sequence of actions: choose two indexes i, j (i ≠ j); perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class Rextester{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st1 = new StringTokenizer(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
br.close();
int n = Integer.parseInt(st1.nextToken());
int k = Integer.parseInt(st1.nextToken());
int[] array = new int[n];
boolean pos = false;
for(int i=0;i<n;i++){
array[i]=Integer.parseInt(st.nextToken());
if(array[i]>=0){
pos=true;
}
}
if(!pos){
Arrays.sort(array);
System.out.println(array[0]);
return;
}
int max=0;
for(int lmax=0;lmax<n;lmax++){
for(int rmax=lmax;rmax<n;rmax++){
int sum=0;
for(int b=lmax;b<=rmax;b++){
sum+=array[b];
}
int[] temp = new int[n-(rmax-lmax+1)];
int p=0;
for(int i=0;i<lmax;i++){
temp[p++]=array[i];
}
for(int i=rmax+1;i<n;i++){
temp[p++]=array[i];
}
Arrays.sort(temp);
int[] temp2 = new int[rmax-lmax+1];
int q=0;
for(int i=lmax;i<=rmax;i++){
temp2[q++]=array[i];
}
Arrays.sort(temp2);
int added = 0,l=k;
for(int i=temp.length-1;i>=0 && l>0;i--){
if(temp[i]>0){
added+=temp[i];
l--;
}
}
int removed = 0;l=k;
for(int i=0;i<temp2.length && l>0;i++){
if(temp2[i]<=0){
removed+=temp2[i];
l--;
}
}
sum-=removed;
sum+=added;
max = Math.max(max,sum);
}
}
System.out.println(max);
}
}
|
Java
|
["10 2\n10 -1 2 2 2 2 2 2 -1 10", "5 10\n-1 -1 -1 -1 -1"]
|
1 second
|
["32", "-1"]
| null |
Java 11
|
standard input
|
[
"two pointers",
"sortings",
"brute force"
] |
ff69d22bc683e5d1d83438585224c774
|
The first line contains two integers n and k (1 ≤ n ≤ 200; 1 ≤ k ≤ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 ≤ a[i] ≤ 1000).
| 1,500 |
In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.