Hello Codeforces!
Greetings from DJ Codestars, the official Coding committee of DJ Sanghvi College of Engineering.
We are back with a very unique and interesting coding contest: CONSIZE, a 2-hour long coding contest!! Here, participants will be given 2 hours to solve 5-6 problem statements, with increasing difficulty.
The twist here is that, the score you get is inversely proportional to the length of your code!
To make things even more interesting, the problem statements will be themed around your favourite Netflix shows. Stand a chance to win super exciting prizes, goodies and subscriptions!
Date : Saturday, November 20, 2021 at 5:00pm IST
Duration : 2 Hours
Registration Link: C++ Java Python
Fill in the form to be eligible for prizes and receive all future announcements/updates
- The duration of the contest is 2 hours and there will be 6 problems for you to solve in increasing order of difficulty.
- The supported languages are :-
a. Python
b. Java
c. C++ - There will be a separate contest for each language. You can take part in multiple contests, but in that case you won't be eligible to receive prizes for any of them.
- Make sure you’ve registered before taking part in the contest or else your score will not be considered on the leaderboard
- The scoring system revolves around the length of your code. The shorter the code the more points you get as long as your code passes all the required test cases. Tabs, newlines and spaces don't contribute to character count.
- You can submit solutions as many times as you'd like, there are no penalties for incorrect submissions. Only your best correct submission will be considered.
- The final decision for judgement will be taken by the committee members. No arguments will be entertained. Plagiarism will not be tolerated. If we suspect anyone of doing so they will be immediately eliminated from the contest.
- Only Indian Participants are eligible for prizes.
So what are you waiting for? Hurry up and register yourselves for the contest.
Editorials
Problem: Kota Anomaly
We need to remove minimum number of beads such that any two neighbouring beads have different colour. Problem boils down to counting number of consecutive pairs of same coloured beads.
E.g. RBBGRR Here, ‘BB’ and ‘RR’ pairs have same coloured beads. After removal of 1 bead from each of the 2 pairs, final string becomes ‘RBGR’.
E.g. RBBB Here, ‘BB’ ( R BB B ) and ‘BB’ ( RB BB ) pairs have same coloured beads. After removal of 1 bead from each of the 2 pairs, final string becomes ‘RB’.
E.g. RBGGBRRRGBBR Here, number of pairs of same coloured beads are 4
(RB GG BRRRGBBR,
RBGGB RR RGBBR,
RBGGBR RR GBBR,
RBGGBRRRG BB R)
After removal of 1 bead from each of the 4 pairs, final string becomes ‘RBGBRGBR’
#include <bits/stdc++.h>
using namespace std;
int main() {
int noOfBeads; cin >> noOfBeads;
string beads; cin >> beads;
int sameColouredPairs = 0;
for (int i = 0; i < noOfBeads - 1; i++)
if (beads[i] == beads[i + 1])
sameColouredPairs++;
// remove 1 bead from each same coloured pairs
int finalNoOfBeads = noOfBeads - sameColouredPairs;
cout << finalNoOfBeads << endl;
return 0;
}
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int noOfBeads = Integer.parseInt(sc.nextLine());
String beads = sc.nextLine();
int sameColouredPairs = 0;
for(int i=0; i<noOfBeads-1; i++){
if(beads.charAt(i) == beads.charAt(i+1)){
sameColouredPairs++;
}
}
// remove 1 bead from each same coloured pairs
int finalNoOfBeads = noOfBeads-sameColouredPairs;
System.out.println(finalNoOfBeads);
}
}
noOfBeads = int(input())
beads = str(input())
sameColouredPairs = 0
for i in range(noOfBeads-1):
if beads[i] == beads[i+1]:
sameColouredPairs += 1
# remove 1 bead from each same coloured pairs
finalNoOfBeads = noOfBeads-sameColouredPairs
print(finalNoOfBeads)
#include<iostream>
char p, c; int a;
int main() {
while (std::cin >> c)
if (c > 64)
a += c != p, p = c;
std::cout << a;
}
import java.util.*;
public class Solution {
public static void main(String[] a) {
Scanner s=new Scanner(System.in);
int n=s.nextInt(),x=1,i;
char[] c=s.next().toCharArray();
for(i=1;i<n;i++)
if(c[i]!=c[i-1])
x++;
System.out.println(x);
}
}
x=input
x()
s=x()
z=a=0
for i in s:
if i != z:
a += 1
z=i
print(a)
Problem: Emily and her team
The solution for this problem requires us to find 4 players that play at each location and check if their cost is within the budget.
We can only print “no” when the sum of the minimums of each position is more than B.
When (Sum of Cheapest GK, mid, defender, forward > B ) we print “no”.
We can create an array of size 4 to store the minimum cost for each position and then iterate over an array that stores the cost of the players and we can check to see if each player's cost is lesser than the minimum cost of a player in that position, thus we find all minimums in the cost array for each position.
We can simply total them and see if the sum is less than the budget given.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
for(int i = 0 ; i < t ; i++){
int n , b;
cin >> n >> b;
vector <int> cost(n) , m(4,100) , code(n);
for(int j = 0 ; j < n ; j++){
cin >> cost[j];
}
for(int j = 0 ; j < n ; j++){
cin >> code[j];
}
//assigning max values to m only because each of them will change
//when compared to a lower value from the cost vector or stay the same
//if the only cost for a certain position is 100
for(int j = 0 ; j < n ; j++){
if(m[code[j]] > cost[j] ){
m[code[j]] = cost[j];
}
}
if(m[0] + m[1] + m[2] + m[3] <= b){
cout << "yes" << '\n';
}else{
cout << "no" << '\n';
}
}
return 0;
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0)
{
int n=sc.nextInt();
int b=sc.nextInt();
int ar[]=new int[n];
int p[]=new int[n];
int mins[]={100,100,100,100};
for(int i=0;i<n;i++)
{
ar[i]=sc.nextInt();
}
for(int i=0;i<n;i++)
{
p[i]=sc.nextInt();
}
for(int i=0;i<n;i++)
{
if(ar[i] < mins[p[i]]){
mins[p[i]] = ar[i];
}
}
if(mins[0] + mins[1] + mins[2]+mins[3] <= b ){
System.out.println("yes");
}else{
System.out.println("no");
}
}
}
}
for i in range(int(input())):
n, b = input().split(' ', 1)
p = input().split()
c = input().split()
for x in range(int(n)):
p[x] = int(p[x])
c[x] = int(c[x])
# f = []
m = [100,100,100,100]
for j in range(int(n)):
# cj = c[j]
if p[j] < m[c[j]]:
m[c[j]] = p[j]
if m[0] + m[1] + m[2] + m[3] <= int(b):
print("yes")
else:
print("no")
#include <bits/stdc++.h>
using namespace std;
int t, n, b, i, x;
int main()
{
cin >> t;
while(t--)
{
cin >> n >> b;
vector<int> a(4, 1e8), p(n);
for(int &x: p) cin >> x;
i = 0;
while(i < n)
cin >> x, a[x] = min(a[x], p[i++]);
for(int x: a) b -= x;
cout << (b < 0 ? "no" : "yes");
}
}
import java.util.*;
public class w
{
public static void main(String args[])
{
Scanner y=new Scanner(System.in);
int t = y.nextInt();
while(t-->0)
{
int n = y.nextInt();
int b = y.nextInt();
int g,m,d,f,c,z;
g = m = d = f = c = z = 101;
int a [][] = new int[2][n];
int i=0;
for(; i<n; i++)
a[0][i] = y.nextInt();
i=0;
for(; i<n; i++)
{
a[1][i] = y.nextInt();
c = a[1][i];
z = a[0][i];
if(c == 0 & z<g)
g = z;
if(c == 1 & z<m)
m = z;
if(c == 2 & z<d)
d = z;
if(c == 3 & z<f)
f = z;
}
String o;
if(g+m+d+f<=b)
o="yes";
else
o="no";
System.out.println(o);
}
}
}
f=lambda:[*map(int,input().split())]
for w in ' '*f()[0]:
n,b=f()
l=[b]*4
for i,j in zip(f(),f()):
l[j]=min(l[j],i)
print('yneos'[sum(l)>b::2])
Problem: Tokyo need Guns
Let's visualize the distances on a number line. This problem can be solved using the following greedy claim:
Keep moving in one direction, reloading guns. It is optimal to switch to the opposite direction at most once.
Proof of claim:
Let O be the origin; A, B, C be 3 points such that A < O < B < C. Let i, j, k be the time taken to reach A, B, C respectively. Say that between A to C (inclusive), there are X guns.
Let t1 be the time required to reload X guns in total if we initially head right then switch left.
Let t2 be the time required to reload X guns in total if we initially head left then switch right.
Case 1: t1 < t2 ⇒ OC + CA < OA + AC
⇒ OC < OA
⇒ i < j
⇒ i < 2k + j
⇒ i + (i + j) < 2k + j + (i + j)
⇒ 2i + j < 2k + 2j + i
⇒ OC + CA < OB + BA + AC
⇒ Time taken when we switch direction once < Time taken when we switch direction more than once
∴ We proved that it is optimal to switch direction not more than once. Case 2 where t1 >= t2, we can prove the same similarly as case 1.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> a, b;
a.push_back(0);
b.push_back(0);
for(int i = 0; i < n; i++) {
int x; cin >> x;
if(x <= 0) {
a.push_back(-x);
} else {
b.push_back(x);
}
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int n1 = a.size();
int n2 = b.size();
int ans = INT_MAX;
for(int i = 0; i < n1; i++) {
int j = k - i;
if(j >= 0 && j < n2) {
ans = min(ans, a[i] * 2 + b[j]);
}
}
for(int i = 0; i < n2; i++) {
int j = k - i;
if(j >= 0 && j < n1) {
ans = min(ans, b[i] * 2 + a[j]);
}
}
cout << ans << '\n';
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
long[] x=new long[n];
for(int i=0; i<n; i++){
x[i]=sc.nextLong();
}
long ans=Long.MAX_VALUE;
for(int i=0; i<=n-k; i++){
ans=Math.min(ans,Math.min(Math.abs(x[i]),Math.abs(x[i+k-1]))+x[i+k-1]-x[i]);
}
System.out.println(ans);
}
}
n,k=map(int,raw_input().split())
x=map(int,raw_input().split())
res=float('inf')
for i in xrange(n-k+1):
l=x[i]
r=x[i+k-1]
res=min(res,abs(l)+abs(r-l),abs(r)+abs(l-r))
print res
#include<bits/stdc++.h>
using namespace std;int n,m,x,y,i,p=1e9,a[1<<20],d,e;int main() {for(cin>>n>>m;i<n;++i)cin>>a[i],i>m-2?x=a[i-m+1],y=a[i],d=abs(x),e=abs(y),p=min(p,(x^y)<0?y-x+min(d,e):max(d,e)):0;cout<<p;}
import java.util.*;
public class S{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
int n=s.nextInt();int k=s.nextInt();int a[]=new int[n];
int i=0;
for(;i<n;i++)a[i]=s.nextInt();
int u=a[k-1]-a[0];int b=u+Math.min(Math.abs(a[0]),Math.abs(a[k-1]));
i=1;
for(;i<=n-k;i++){
u=u-(a[i]-a[i-1])+(a[i+k-1]-a[i+k-2]);b=Math.min(b, u+Math.min(Math.abs(a[i]),Math.abs(a[i+k-1])));}
System.out.print(b);}}
n,x,*a=map(int,open(0).read().split())
t=x-1
print(min(a[i+t]-a[i]+min(abs(a[i]),abs(a[i+t]))for i in range(n-t)))
Problem: Old Jonas loves Young Martha
We can assume that A1 <= A2 <= ... <= AN by sorting the input. Then for each i < j, |Ai — Aj| = Aj- Ai holds true.
For each i,
$$$\Sigma_{j=i+1}^N \lvert{A_i-A_j} \rvert = (\Sigma_{j=i+1}^N A_j) - (N-i)\cdot A_i $$$
and this can be calculated in a O(1) time each by calculating the cumulative sums beforehand also known as suffix sum in this case. Therefore, the problem can be solved in a total of O(NlogN) time.
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define all(v) (v).begin(),(v).end()
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<int> arr(n);
for(int i=0; i<n; i++) cin >> arr[i];
sort(all(arr));
vector<int> suff_arr = arr;
for(int i = n-2; i>=0; i--){
suff_arr[i] += suff_arr[i+1];
}
int res = 0;
for(int i = 0; i < n-1; i++){
res += (suff_arr[i+1] - arr[i] * (n - i - 1));
}
cout << res << "\n";
return 0;
}
import java.util.*;
import java.io.PrintWriter;
class Main {
public static void main(String[] Args) {
var sc = new Scanner(System.in);
var out = new PrintWriter(System.out);
var N = Integer.parseInt(sc.next());
var A = new long[N];
for (var i = 0; i < N; i++) {
A[i] = Long.parseLong(sc.next());
}
Arrays.sort(A);
var sumA = new long[N + 1];
sumA[N] = 0;
for (var i = N - 1; i >= 0; i--) {
sumA[i] = A[i] + sumA[i+1];
}
long diff = 0;
for (var i = 0; i < N - 1; i++) {
diff += sumA[i + 1] - (A[i] * (N - i - 1));
}
out.println(diff);
out.flush();
}
}
N = int(input())
A = list(map(int, input().split()))
A.sort()
ans = 0
suma = sum(A)
for i in range(N-1):
suma -= A[i]
ans += abs(A[i]*(N-i-1) - (suma))
print(ans)
#include<bits/stdc++.h>
using namespace std;
int main()
{
long n,b=0;
cin>>n;
long a[n],s=n-1,i=n;
while(i--)
cin >> a[i];
sort(a,a+n);
for(i=0;i<n;i++)
b-=s*a[i],s-=2;
cout << b;
}
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int i,n=s.nextInt();
long a[]=new long[n],z=0;;
for( i=0;i<n;i++)
a[i]=s.nextInt();
Arrays.sort(a);
for( i=0;i<n;i++){
z+=i*a[i]-(n-1-i)*a[i];
}
System.out.println(z);
}
}
n,*s=map(int,open(0).read().split())
s.sort()
print(sum(s[i]*(2*i-n+1) for i in range(n)))
Problem: Ammo Expectation
Can we use linearity of expectations?
Can we use Euler's Totient Function?
Let E(X) denote the expected value of random variable X.
Here, X denotes the amount of ammo that the faction takes away.
Let Xi be the value of ammo that member i wins.
Then, X = X1 + X2 + .. + Xn
Using linearity of expectations, we can say that
E(X) = E(X1) + E(X2) + .. + E(Xn)
So the problem can be solved by summing up the expected ammo won by individual members. Let's see how we can find the individual expectations.
Euler's totient function, also known as phi-function ϕ(n), counts the number of integers between 1 and n inclusive, which are coprime to n.
If i and j operate the machine, the probability that they win ammo is $$$\frac{ϕ(A_i·A_j)}{A_i·A_j}$$$
ϕ(i) can be calculated ∀ i ∈ [1,m] where m = max(Ai) in O(mloglog(m)) time. It can also be calculated in O(mlog(m)) which takes less characters of code to write, but takes more time (enough to pass in time limit though). The product Ai·Aj can be as large as 1012, so we cannot calculate all ϕ(i) values upto 1012. Hence we exploit the following property of phi function:
ϕ(a·b) = ϕ(a)·ϕ(b)· $$$\frac{gcd(a,b)}{ϕ(gcd(a,b))}$$$
It is now sufficient to calculate ϕ(i) ∀ i ∈ [1,m], as we can obtain ϕ(Ai·Aj) by plugging the computed values of ϕ(Ai), ϕ(Aj) and ϕ(gcd(Ai,Aj)) in the equation above. Final answer will be
∴ E(X) = ($$$\frac{ϕ(A_N·A_1)}{A_N·A_1}$$$ + $$$\Sigma_{i=1}^{N-1}$$$ $$$\frac{ϕ(A_i·A_{i+1})}{A_i·A_{i+1}}$$$)·K
We will find gcd of adjacent pairs N times, finding gcd(A,B) takes O(log(A·B)) time.
∴ Time complexity of solution will be O(mlog(log(m))+nlog(m)) or O(mlog(m)+nlog(m)) depending on the implementation of calculating phi function.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
vector<ll> calc_ETF(int n) {
vector<ll> phi(n+1);
phi[0] = 0;
phi[1] = 1;
for (int i = 2; i <= n; i++)
phi[i] = i;
for (int i = 2; i <= n; i++) {
if (phi[i] == i) {
for (int j = i; j <= n; j += i)
phi[j] -= phi[j] / i;
}
}
return phi;
}
void solve() {
int n; ll k; cin >> n >> k;
ll mx = 0;
vector<ll> arr(n);
for (auto& i: arr) {
cin >> i;
mx = max(mx, i);
}
vector<ll> phi = calc_ETF(mx);
vector<ld> E(n+1);
for (int i = 0; i < n; i++) {
ll A = arr[i], B = arr[(i+1)%n];
ll g = __gcd(A,B);
ll num = (phi[A] * phi[B] * g) / phi[g];
ld den = A * B;
ld val = num / den;
E[i] += val;
E[(i+1)%n] += val;
}
ld ans = 0;
for (auto i: E) ans += i;
ans *= k;
cout << fixed << setprecision(6) << ans << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
}
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Main {
public static int gcd(int x, int y){
return (y == 0) ? x : gcd(y, x % y);
}
public static void main (String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long k = sc.nextLong();
int arr[] = new int[n];
int mx = 0;
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
mx = Math.max(mx, arr[i]);
}
int phi[] = new int[mx+1];
phi[1] = 1;
for (int i = 2; i <= mx; i++)
phi[i] = i;
for (int i = 2; i <= mx; i++) {
if (phi[i] == i) {
for (int j = i; j <= mx; j += i)
phi[j] -= phi[j] / i;
}
}
BigDecimal ans = new BigDecimal("0");
for (int i = 0; i < n; i++) {
int A = arr[i], B = arr[(i+1)%n];
int g = gcd(A,B);
long num = (( ((long)phi[A]) * ((long)phi[B]) * ((long)g))) / ((long)phi[g]);
long den = A * B;
BigDecimal d = new BigDecimal((double) ((double) num * 2l) / ((double) den));
ans = ans.add(d);
}
ans = ans.multiply(new BigDecimal(k));
System.out.print(String.format("%.6f", ans));
}
}
import math
from decimal import Decimal
def calc_ETF(n):
phi = [0] * (n+1)
phi[0] = 0
phi[1] = 1
for i in range(2,n+1):
phi[i] = i
for i in range(2,n+1):
if phi[i] == i:
for j in range(i,n+1,i):
phi[j] = phi[j] - phi[j]//i
return phi
n ,k = map(int, input().split())
arr = list(map(int, input().split()))
mx = arr[0]
for i in arr:
mx = max(mx, i)
phi = calc_ETF(mx)
ans = 0
for i in range(n):
A = arr[i]
B = arr[(i+1)%n]
g = math.gcd(A,B)
num = (phi[A] * phi[B] * g) // phi[g]
den = A * B
val = Decimal(num * 2) / Decimal(den)
ans = ans + val
ans = ans * k
print ('%.6f'%ans)
#include<bits/stdc++.h>
using namespace std;long double ans;int main() {int N=1<<20,n,k,phi[N],a[N],x,y,d,i,j;iota(phi,phi+N,0);for(i=1;i<N;++i)for(j=i+i;j<N;j+=i)phi[j]-=phi[i];cin>>n>>k;for(i=0;i<n;++i)cin>>a[i];for(i=0;i<n;++i)x=a[i],y=a[(i+1)%n],d=gcd(x,y),ans+=(long double)phi[x]/x*phi[y]/y*d/phi[d];printf("%.9Lf",ans*2*k);}
Nobody :(
from decimal import *
n,k,*a=map(int,open(0).read().split())
m=4**10
p=[1]*m
s=[set()for i in' '*m]
for i in range(2,m):
if p[i]:
for j in range(i,m,i):
p[j]=0
s[j]|={i}
r=0
for x, y in zip(a, a[1:]+[a[0]]):
z=m=Decimal(x*y)
for i in s[x]|s[y]:
z-=z//i
r+=k*2*z/m
print(r)
UPD 1: Rule 3 has been updated.
UPD 2: Editorial for Ammo Expectation has been added, with shortest codes. Editorials and shortest codes for other problems will be added soon.
UPD 3: Editorials and Shortest Code Submissions have been added for all problems
great , damn excited to take part in it
Ara Ara... :).
It's coinciding with Atcoder ABC Contest please change the timeing?
Sorry, we won't be able to do that
Different Codegolf contest link for every language? This is something unique!
Interesting idea! What is the exact criteria/formula for awarding score on basis of length of code? Looking forward to participate!
The score assigned will be Sum $$$\sum_{}^{} k/(number Of Characters)$$$ over all accepted test cases. Here $$$k$$$ is a constant.
I'm considering choosing either Python or C++ but I want to do the one with more people (because that'll have more competition :) so will we know how many people signed up for each language?
Also, why can we not register for multiple languages? If I'm not from India I won't be receiving any prizes anyway, so there won't be the problem of one person getting first in all three. Perhaps you could add an option "Register but with no prize" for other languages?
At the moment we have maximum signups for C++, followed by Python and then Java.
Yes you can participate in multiple contests, however you won't be considered for prizes in any of them. The changes can now be seen in Rule 3.
Can you elaborate on what the prizes will be and how many will be eligible for the prizes?
Top 2 winners in each language will win goodies, vouchers, and discounts
score you get is inversely proportional to the length of your code!
yash_chad please clarify what do you mean by length of code.
Is score will be given by the
number of characters
ornumber of lines
in codeRule 5 says "The scoring system revolves around the length of your code. The shorter the code the more points you get as long as your code passes all the required test cases. Tabs, newlines and spaces don't contribute to character count."
So only count of characters count (excluding tabs, newlines and spaces)
As dedsec_29 mentioned, the score will be inversely proportional to the number of characters in your code!
Excited to take part in this event!!
Are ties broken by number of problems solved or time taken ?? .
First the summation of total score of all questions solved by the participant is considered, if there's still a tie then it is resolved by the time taken
I filled the registration form and received an email confirmation for the contest registration. However, no link to the contest appears in my HackerRank account. Am I missing something?
The link to the contests is given in this post itself, you need to use the same link you used for registration
Thanks for the information. I found the link and participated in the contest.
I have a feeling that the problem names are
just guessing....
Its a hackerrank bug guys... relax lol
Could we get an explanation for the sample case in problem 4?
I'm getting $$$383$$$ as the answer instead of $$$253$$$:
and $$$114+104+86+53+26 = 383$$$. After just the first three rounds, my answer is already more than $$$253$$$.
I can't see why it's 253It's likely that I'm doing something wrong, so could you please add an explanation for what happens after the $$$1^\textrm{th}$$$ universe is deleted? An explanation for the entire process would be too long, so perhaps just for one more universe-deletion.Edit: Nevermind, it has just been added.
Note: In the input format it says
shouldn't the indexing start from $$$1$$$ instead of $$$0$$$?
We are really sorry for the inconvenience, the problem statement has been updated
damm i was able to solve 4 problem but i don't know about expected value and it's calculation
can somebody provide me a good tutorial or blog where i can learn this concept
Thanks for the contest!
I am the winner of the Python contest (I'm not Indian so I'm ineligible for prizes), and managed to get the shortest in-contest python codes on all problems apart from the first one. I thought I'd share my codes here.
Interesting how we reached almost exactly the same code!
Note that I forgot whitespace wasn't counted so I was using semicolons everywhere until almost the end, oops. Also I didn't change a few things that would've reduced the char count.
1) I used
input()
instead of yourf()
because I didn't have enough time to change it :( otherwise it's exactly the same. Nice how you can cast a bool to an int in Python.2) Added just now, but the following is shorter:
Mainly it's because changing the for-loop to a while loop is shorter. Also note the clever unpacking in
t,=P()
by using the comma equals operator3) Two seconds too late, the following is shorter:
Note that using
instead of the first three lines is shorter. It got me 75.8 points.
4) I was doing something slightly different, but I guess it ended up producing a longer solution:
Ugh those semicolons againUsing your method and tweaking it a bit (walrus operator!) it's a little shorter:
5) I improved a few things to get this:
Note that the
p
array to check if a number is prime is redundant, because we can just check that the length of the prime factors sets[i]
has length 0.I especially don't like that we need to use
decimal.Decimal
because of precision errors. The constraints should have been lowered instead.Here are the stats of my submissions:
I believe that the solution for 1 is optimal, but I want to keep trying to golf the rest.
Very cool, nice optimisations! Congrats on second place too!
I spent most of the contest trying to debug problem 5, and only realised near the end of contest that I should have used the Decimal class (oops, should have thought of that earlier). So most of my time was spent debugging, not optimising the rest of the code. For most of the contest, my codes were not the shortest. Only in the last 15 or so minutes of the contest did I go back over my old codes and add optimisations such as
Also, looking at the leaderboard, I had so many points over the rest of the competitors that I didn't really have the motivation to grind for tiny optimisations with little score change. This was especially due to the fact that nobody else got AC on all test cases on problem 5 using python during the contest (I presume; either that, or the other person had extremely long code).
Finally, somebody got a score of 60.0 during the contest for Problem 1, so my solution is definitely not optimal. I would be extremely curious to know what the optimal solution is!
Can't wait for a similar contest in the future! (Hopefully someone makes one soon)
The following code gives 63.8 points on problem 1: Walrus operator to the rescue!
Great contest, i secured 4th rank. Kudos to abhinav sharma. My c++ codes:
What is the time complexity of your code for Ammo Expectation, is it O(n * log(m) * m)? m being max(Ai)
Here $$$h(n)$$$ is the phi function used from cp-algorithms. It's time complexity is $$$O(\sqrt{n})$$$. Overall time complexity is thus $$$O(n\sqrt{m})$$$.
You are calculating phi of values as big as 1012 along with gcd, total N times. Calculating phi using the sqrt algorithm will take O(sqrt(m2) + log(m)) time, i.e. O(m + log(m)) => O(m). Overall time complexity of your code seems to be O(n * (m + log(m))) => O(n*m)).
Your code shouldn't pass in the time limit, but it did pass :0
I had tried submitting O(n * (m + logm)) solution too but it TLEd. I think your solution shouldn't have passed. Is there anything wrong with my analysis?
No h(a) is only called for value <= 10 ^ 6. I have used h(a, b) for calculating phi(a * b) which as time complexity O(sqrt(max(a, b)).
Oh I missed that, my bad. Your solution then seems to be O(n*sqrt(m)), roughly 106 * 103 = 109 calculations. I still think it shouldn't have passed, test cases should've been tighter. Let me know again if I have analyzed anything incorrectly
My thoughts on the contest:
It was a very unique idea to have codegolf + competitive programming + 2 hours for the contest. I thought it was very fun.
Also, maybe if you do this again, have the contest be longer? I still feel like I had more to golf but the time was up. I think 3 hours would be better.
Note: Having the score depend on code size actually presented a decision to make: Do I reduce the size of the code for this problem or this other one? I really liked this aspect of the contest.
I missed the submission of the third problem by 2 seconds, which would've given me 9 more points. Luckily that didn't make me go down in the standings though!
Thank you for your feedback on the contest!
Sure, we will keep this in mind to have a longer contest of 3 hours next time, maybe with 6 problems? Or 5 problems but with higher difficulty. Let us know what you think sounds more fun
I don't think the problems should be made any harder — the contest is mainly a code golf contest, not a CP contest, and if the problems are made any harder, there may not be enough time for optimising code length. Already as it is, for the Python contest, only 3 users scored any points on the last problem, despite it not being particularly difficult (and I believe I was the only one who passed all test cases, although that was probably more due to precision errors than problem difficulty).
Interesting contest, but the scoring system has a big issue — spaces and tabs can represent data, they shouldn't be simply ignored.
Here's a demo: Python code. It uses only "67 characters", and achieves full score easily on Ammo Expectation. However, the real code is encoded as binary text, and replaced with tab and space.
Yes, and it's on cses as well. I sent a dm to pllk a while back, so hopefully it'll be fixed soon. I was talking about Ruby but the same can be done, as you've shown, in Python. In essence, I suggested the following ideas:
The best solution would just be to count whitespace as well though. Perhaps only count
\r\n
as one character though.I think we may count the spaces in strings, and disable the program from reading its own source code.
Counting all whitespaces is a good solution, but I think it increases coding difficulty, and is not the best option for a 2 hour contest.
I am surprised that contestants can exploit encoding into spaces. Thanks for bringing this to our attention. Counting all whitespace seems like a good idea. Also taken Ritwin's suggestions. We will experiment with the hackerrank custom_checker to score without letting the program read its own source code. I am not so sure how to achieve this right now.