The post CodeKnights.org appeared first on IIUM ICPC Team.

]]>Next Saturday is CodeKnights Round 19. Which mean, very soon, I will not have enough finger on my hands and feet to count the number of rounds we had. When you think about it, its been more than 9 months since we started CodeKnights! How time flies. Because of this, we are now making a new website specially for CodeKnights.

CodeKnights new domain:

So check it out. Its a bit plain for now, but new things will starts to pop up soon. We are still going to use our old contest system. Those things are too complex to be built in a short time. However, for registration, we are no longer using the old google forms. And that also means that the **old registration is no longer valid**. Which means you will need to** re-register again** **using the new website**. If you don’t register, you can’t participate on the next round. The good thing is, you can now change your username or password whenever you like.

The creation of the new website is to help us manage and improve CodeKnights. When you have this much rounds, certain things are getting quite unwieldy. Getting the rankings from previous round can be a chore or even impossible. Some people registered twice (or even thrice?) to change their username and password. Some people specified their university name using acronym, some do not, some uses acronym with small letter. Sometimes we forgot to announce a round and sometimes we don’t remember which round is it. We have about 145 registrations (not counting the previous DSA students), but not even a quarter of that is participating. Even, the question “when was round 15?” is a hard question to answer.

In fact, I’m sure you guys have your fair share of criticism. And it would be very helpful if you could voice it out in the comment sections below. We take all feedback constructively.

So that’s all folks! Thank you for reading. Good bye and Assalamualaikum.

The post CodeKnights.org appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 14 Result and Problem Analysis appeared first on IIUM ICPC Team.

]]>Anyway, Round 14 is the second round after the last round which IIUM’s DSA student is scored for participation. Additionally, its kinda exam period for IIUM student… so… we are seeing a much lower participation, even after including participant from Hebron University, Palestine. In fact, looking at the ranking list, 6 out of 10 participant actually came from Hebron! If they did not participate, we would be looking at only 4 participant!

Anyway, back to the matters at hand, the winner of this round is.. not stdLn. Its capayam (formerly known as shahril). Both him and stdLn solved 3 out of 5 question, although I can personally say that capayam nearly solved C. Congratulation to capayam. Their name will forever be carved in the newly created Code Knights Hall of Fame, at least until I run out of money to pay for this server. Just kidding, Amjad would pay for it if I can’t afford to do so. On to the solutions:

This is a giveaway problem and its looks like everyone solved it. Giveaway requirement, achieved! Although the task says that you need to figure out how many swap is needed, the output does not requires it. You just need to output the used characters in upper case. Which means, you don’t actually need to swap and do things as the question asked you too. Its a trick to make you think too hard and stress you out!

#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<ll,ll> pii; #define REP(i,n) for(ll i=0;i<n;i++) #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x << endl; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif int main(){ set<char> sets; string s; cin >> s; for(char c: s){ if(c <= 'z' && c >= 'a'){ c -= 'a'-'A'; }else{ } sets.insert(c); } for(char c: sets){ cout << c; } }

The problem involve detecting if the rows are sorted or not, then swap them with the last row. You must do this one after another. I did not understand the (lack of) story or the rational of this problems. But if you do it as ordered, you should be fine. I personally got into trouble thinking that by “sorted” it need to be strictly increasing or decreasing. It does not need to be so. If all the numbers in a row is the same, it is considered to be sorted.

#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<ll,ll> pii; #define REP(i,n) for(ll i=0;i<n;i++) #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x << endl; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif int main(){ int rows[3][3]; int inOrder[3]; REP(i, 3){ cin >> rows[i][0]; cin >> rows[i][1]; cin >> rows[i][2]; if(rows[i][0] <= rows[i][1] && rows[i][1] <= rows[i][2]){ inOrder[i] = true; }else if(rows[i][0] >= rows[i][1] && rows[i][1] >= rows[i][2]){ inOrder[i] = true; }else{ inOrder[i] = false; } } if(!inOrder[0]){ REP(i, 3){ swap(rows[0][i], rows[2][i]); } } if(!inOrder[1]){ REP(i, 3){ swap(rows[1][i], rows[2][i]); } } REP(i, 3){ cout << rows[i][0] << " " << rows[i][1] << " " << rows[i][2] << endl; } }

I was thinking about the fact that many people criticize competitive programming due to the lack of practical use of all these algorithms/technique that we use. Its not that these knowledge are useless, its just that only a handful of (well paid) programmer need to actually know these stuff. Most of us would just use what these people had created. So I want to make a problem that you may actually encounter in your everyday life, in this case, parse an input whose format is inconsistent. The (suggested) solution for this problem involve using a regular expression, which you are more likely to use in real life than say… a binary search. Unfortunately it turns out, the C++ compiler on the server does not support C++11’s regular expression. So, you’ll need to use python or java to solve this problem. Admittedly, the constraint and explanation of the problem need more work, but hey, I have to start somewhere.

import java.io.PrintStream; import java.util.*; import java.io.*; import java.util.regex.*; public class Main{ static Scanner in; static PrintStream out; static PrintStream err; static { in = new Scanner(System.in); out = System.out; err = System.err; boolean enable_debug = true; if(!enable_debug){ err = new PrintStream(new OutputStream(){ public void write(int b){ // NO-OP } }); } } public static <T> void dbg(String s,T val){ err.print(s+": "); err.println(val); } public static void main(String[] args){ Pattern p = Pattern.compile("^[^:]+: *([0-9]+) *: *[^0-9\\.]*([0-9\\.]+) *$"); double total = 0; while(in.hasNextLine()){ String line = in.nextLine(); Matcher m = p.matcher(line); if(m.matches()){ int quant = Integer.valueOf(m.group(1)); double amount = Double.valueOf(m.group(2)); total += quant*amount; } } out.println(total); } }

This is a classical dynamic programming problem, the range sum problem. Its pretty well known and can be considered ‘elementary’ for dynamic programming, although it can be unclear how can this be considered dynamic programming. Some of you uses a segment tree to solve this, which do work, but overkill. The trick is, for each query, you should not actually count the numbers between the two range. That would be too slow. Instead, you first create an array of cumulative sum of the original array. With that, you can get the answer for each query in constant time by simply subtracting the cumulative sum at the end of the range with the cumulative sum at the start of the range. See the code for more information.

#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<ll,ll> pii; #define REP(i,n) for(ll i=0;i<n;i++) #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x << endl; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif int main(){ int n; cin >> n; int nums[n+1]; nums[0] = 0; REP(i, n){ cin >> nums[i+1]; } REP(i, n){ nums[i+1] += nums[i]; } int q; cin >> q; REP(iq, q){ int l, r; cin >> l >> r; cout << nums[r] - nums[l-1] << endl; } }

Have you ever found a problem where you think that there is no way that would work and then you read the tutorial and found a valid solution with a perfectly reasonable explanation? Well, if you did not solve this problem, then this is that kind of problem. First, the limit for A and B is actually much higher, up to the limit of 32 bit integer which is about 2*10^9. So, a normal sieve of aristotle would take too much memory and time. The limit specified which is 10^6 is the different between A and B. Naturally, you would think of iterating from A to B and checking for primes. But how would you check for the primes? You can’t create a sieve of size 10^9 to directly check if that number is a prime. The trick is, to determine if a number is prime or not, you can check if the number is divisible by any prime number lower that the square root of that number. If no prime number within that range can divide the number, the number must be a prime. There is a proof for it, but I’ll let you sleep on it. That means with all the prime numbers less than 2^18, you can effectively check if a number less than 2^32 is a prime number or not. Check the solution for more information. Fun fact: if I pass a `long long`

to the `isPrime`

function instead of an `int`

, it would actually take twice the time, which means it may get TLE.

#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<ll,ll> pii; #define REP(i,n) for(ll i=0;i<n;i++) #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x << endl; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif #define SIEVE_SIZE 100001 bool sieve[SIEVE_SIZE]; vector<int> primes; ll compcount = 0; bool isPrime(int num){ if(num <= 1) return false; int lim = sqrt(num)+1; for(int i=0;i<primes.size() && primes[i] < lim;i++){ if(num%primes[i] == 0) return false; } return true; } void solve(ll a, ll b){ pii lowest = {-1, INT_MAX-100}; pii highest = {-1, -1}; ll lowDiff = INT_MAX; ll highDiff = 0; ll prev = -1; ll next = -1; for(ll i=a;i<=b;i++){ if(isPrime(i)){ if(prev == -1){ prev = i; }else{ next = i; ll diff = next-prev; if(diff < lowDiff){ lowest = { prev, next }; lowDiff = diff; } if(diff > highDiff){ highest = { prev, next }; highDiff = diff; } prev = next; } } } if(lowest.first == -1){ printf("No two primes exist\n"); }else{ printf("Closest = %d,%d and Furthest: %d,%d\n", lowest.first, lowest.second, highest.first, highest.second); } } int main(){ REP(i, SIEVE_SIZE){ sieve[i] = 0; } //cerr << "gen " << endl; for(ll i=2;i<SIEVE_SIZE;i++){ if(sieve[i]) continue; //cerr << "gen " << i << endl; primes.push_back(i); for(ll j=i*i;j<SIEVE_SIZE;j+=i){ sieve[j] = true; } } assert(isPrime(11)); assert(isPrime(13)); assert(isPrime(17)); int a, b; while(cin >> a >> b){ solve(a, b); } }

This round is rather typical. Unfortunately, the turnup is quite low. Not sure what should I do to bring it up. Maybe I should giveaway my ‘mi band pulse’ to the winner which I never use anyway, if only I could find it… Again, I want to reiterate that 60% of this round’s participant (which is only 6 people) is from Palestine. So, only 4 participant is from Malaysia. Wait.. stdLn is a Bangladeshi, which means there are only 3 Malaysian here (assuming kinah_97 and sir_zia is a Malaysian)… hmm.. the terms “for Malaysia’s University student” is getting rather blurry. At least capayam won. Anyway, will we see an increase in participation next week? Or will we see an increase in Palestinian participation next week, forcing us to change Code Knights home country to Palestine? Either way, I still can’t find my ‘mi band pulse’. Tune in next week for Round 15 and for more… drama!… Or I’ll end up not making another analysis.. who knows?…

The post Code Knights Round 14 Result and Problem Analysis appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 10 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>#include <iostream> using namespace std; int n ; int tmp; int tallest = 1 ; int shortest = (1<<31)-1; int main(){ cin >> n ; for(int i=0;i<n;i++){ cin >> tmp; if ( tmp > tallest ) tallest = tmp; if ( tmp < shortest ) shortest = tmp; } cout << tallest << " " << shortest << endl; return 0; }

#include <iostream> #include <algorithm> using namespace std; int n ; int a[1000001]; int main(){ cin >> n ; for(int i=0;i<n;i++){ cin >> a[i]; } sort(a,a+n); reverse(a,a+n); cout << a[0]; for(int i=1;i<n;i++){ cout << " " << a[i]; } cout << endl; return 0; }

#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<ll,ll> pii; #define REP(i,n) for(ll i=0;i<n;i++) #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x << endl; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif int main(){ int n; cin >> n; set<int> graph[n]; REP(i, n){ int c; cin >> c; REP(j, c){ int d; cin >> d; d--; graph[i].insert(d); } } int k; cin >> k; vector<int> instructions; REP(i, k){ int d; cin >> d; d--; instructions.push_back(d); } bool valid = true; int cur = instructions[0]; for(int i=1;i<instructions.size();i++){ int next = instructions[i]; if(graph[cur].find(next) == graph[cur].end() && next != cur){ valid = false; break; } cur = next; } if(valid){ cout << "Instruction is OK" << endl; }else{ cout << "This instruction will lead you astray" << endl; } }

#include <iostream> using namespace std; #define ll long long #define MX 20 ll fact[MX+1]; int main(){ fact[0]=1; for(int i=1;i<=MX;i++) fact[i] = fact[i-1]*i; int k,n,q; cin>>k>>n>>q; int pk; ll co; while(q--){ co = fact[n]; for(int i=0;i<k;i++){ cin>>pk; co /= fact[pk]; } cout<<co<<endl; } return 0; }

#include <bits/stdc++.h> using namespace std; int main(){ int t, n = 12, input; int de[100], f[100]; de[0] = 1; f[0] = 1; de[1] = 0; f[1] = 1; for(int i=2 ; i<=n; i++){ de[i] = (i-1) * (de[i-1]+de[i-2]); f[i] = f[i-1]*i; } cin >> t; while(t--){ cin >> input; cout << de[input] << "/" << f[input] << endl; } return 0; }

The post Code Knights Round 10 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 10 appeared first on IIUM ICPC Team.

]]>This is an announcement for Code Knights Round 10. If this is the first time you heard of **Code Knights**, please checkout this link. The short version is that, we are organizing a competitive programming rounds every two weeks open to all Malaysian university student. We do this for practice, education and mostly for the fun of it.

The competition will be held online, similar with various other competitive programming platform such as codeforces and hackerearth, except the difficulty is tuned down to cater for beginner. You can use C, C++, Python or Java. There will be 5 problem to be solved with varying difficulty.

**Date:** 5th November 2016

**Time:** 8PM to 12 AM Malaysian Time

**Venue:** Online (Link will be given later)

**Registration fees:** * FREE *

**Registration link for DSA students:** https://goo.gl/forms/pecD8HUbhsSAta6B2

**Registration link:** http://goo.gl/forms/VJFvSmekoH2Uox203

**Feedback form:** https://goo.gl/forms/Mm1yGOM3dL8hWY0w1

If you want to participate in Code Knights, please fill up your details in the google forms link above. Register once, and you will be registered for all future rounds. We will remind you on the rounds through emails and whatsapp group. Please register before 6 pm on the day of the competition as I have to input your login information into the system. If you have any question, feel free to comment down below.

The post Code Knights Round 10 appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 9 appeared first on IIUM ICPC Team.

]]>This is an announcement for Code Knights Round 9. If this is the first time you heard of **Code Knights**, please checkout this link. The short version is that, we are organizing a competitive programming rounds every two weeks open to all Malaysian university student. We do this for practice, education and mostly for the fun of it.

The competition will be held online, similar with various other competitive programming platform such as codeforces and hackerearth, except the difficulty is tuned down to cater for beginner. You can use C, C++, Python or Java. There will be 5 problem to be solved with varying difficulty.

**Date:** 15th October 2016

**Time:** 8PM to 12 AM Malaysian Time

**Venue:** Online (Link will be given later)

**Registration fees:** * FREE *

**Registration link for DSA students:** https://goo.gl/forms/pecD8HUbhsSAta6B2

**Registration link:** http://goo.gl/forms/VJFvSmekoH2Uox203

**Feedback form:** https://goo.gl/forms/Mm1yGOM3dL8hWY0w1

If you want to participate in Code Knights, please fill up your details in the google forms link above. Register once, and you will be registered for all future rounds. We will remind you on the rounds through emails and whatsapp group. Please register before 6 pm on the day of the competition as I have to input your login information into the system. If you have any question, feel free to comment down below.

The post Code Knights Round 9 appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 7 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>Last Saturday, the 7th round of Code Knights was held, with a total of….. 12 participants. The problems of this round are prepared without proper care due to last minute changes in internal schedule (Eidul Adha specifically). I am not quite sure how to classify this last round. Anyways, we move on and hopefully prepare better ones in the future.

How hard? Well.. I don’t know. The winner for this round goes to anas_95 from IIUM, who also won last round. anas_95 was the only participant who manage to solve 4 problems, but he did not solve problem D. It’s nice to see someone from IIUM winning again, but its starting to get boring. Can someone else win next time? stdLn maybe? Heck, I’m even waiting for lim2481284 to make a comeback.

You can find the dataset and PDF through the link below.

Like last time, before you go to the tutorial, please take some moment to fill up our feedback form.

This problem is classified as giveaway problem. In fact the problem is explanatory type of problems where the description of the problem and the solution is provided in the problem statement. Although, the solution is provided in the problem statement, a few of the contestants could not solve it for some reason (They may have thought it is a trap or the name binary search could be scary enough to not want to solve it) or could be other reasons that I do not know. The problem utilizes binary search which is much more faster than linear search. If you try to solve the problem with linear search, you will end up with TLE verdict (Time limit exceeded). Therefore, binary uses [math]log n[/math] operation to quickly find elements in a sorted array.

**C++ Solution**

#include <bits/stdc++.h> using namespace std; #define ABS(x) ((x)<0 ? -(x) : (x)) #define REP(i,n) for(int i=0, _e(n); i<_e; i++) #define FOR(i,a,b) for(int i(a), _e(b); i<=_e; i++) #define FORD(i,a,b) for(int i(a), _e(b); i>=_e; i--) #define FORIT(i, m) for (__typeof((m).begin()) i=(m).begin(); i!=(m).end(); ++i) #define SET(t,v) memset((t), (v), sizeof(t)) #define ALL(x) x.begin(), x.end() #define UNIQUE(c) (c).resize( unique( ALL(c) ) - (c).begin() ) #define inf_int (1<<31)-1 #define inf_long (1<<63)-1 #define sz size() #define pb push_back #define VI vector<int> #define VS vector<string> typedef long long LL; typedef long double LD; typedef pair<int,int> pii; #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x ; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif int main(){ int n, a[2*100000], q, queryValue; int index; cin >> n ; for(int i=0;i<n;i++){ cin >> a[i]; } sort(a,a+n); cin >> q ; for(int i=0;i<q;i++){ cin >> queryValue; index = upper_bound(a,a+n,queryValue) - a; cout << n - index << endl; } return 0; }

**Java Solution**

import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; import java.util.TreeSet; public class Main{ public static void main(String args[]){ Scanner in = new Scanner(System.in); PrintStream out = System.out; int n = in.nextInt(); int[] inputArrays = new int[n]; for(int i=0; i<n ; i++){ inputArrays[i] = in.nextInt(); } Arrays.sort(inputArrays); int q = in.nextInt(); while(q>0){ int query = in.nextInt(); int index = indexOfHigherThanQuery(0,n-1,query,inputArrays); out.println(n - index); q--; } } public static int indexOfHigherThanQuery(int first, int last, int target,int array[]){ int tmp ; int counter, step ; counter = last+1 - first; while(counter>0){ tmp = first ; step = counter/2; tmp = tmp + step ; if ( !(target < array[tmp]) ){ first = ++tmp; counter -= step + 1; } else counter = step ; } return first; } }

The purpose of this problem was to introduce operator overloading and its usage with the built in sort function in both C++ and Java.

The first task is to write the overloading function which needs 3 doubles and 1 int to do the comparison, passing this 3 doubles and 1 int can be done in multiple ways, in this solution we used a custom struct/object to store them together and then sent the struct/object instance as parameter to the overloading function.

Once the function is complete we just need to use the built-in sort function in C++/Java and sort it, time complexity of the built-in sort is O(n*logn), this will work. If you implement a sorting algorithm with O(n*n) time complexity, then it will get Time Limit Exceeded verdict.

Check out the sample solution to further understand how to do operator overloading in C++, Java doesn’t support operator overloading, its a bit different, check the sample Java source code.

**C++ Solution**

#include <bits/stdc++.h> using namespace std; #define eps 0.001 // This is the custom data container for this solution struct Frog{ double h,w,l; // h->height, w->weight, l->length of jump int i; // i-> position in the original list Frog(){} // Empty Constructor, it is needed for sorting using sort function Frog(double _h, double _w, double _l, int _i){ h = _h; w = _w; l = _l; i = _i;} // Constructor for initializing // The following function defines the nature of the operator overloading // In this case the operator is the comparison function, defined by "()" symbol bool operator()(const Frog& a, const Frog& b){ // The follwing conditions decides whether 'a' should go before 'b' or not if(a.h<b.h){ return false; }else if(abs(a.h-b.h)<eps){ if(a.w>b.w){ return false; }else if(abs(a.w-b.w)<eps){ if(a.l<b.l){ return false; }else if(abs(a.l-b.l)<eps){ return a.i<b.i; } } } return true; } }; int main(){ int n; scanf("%d",&n); vector<Frog> frogs; double h,w,l; for(int i=0;i<n;i++){ scanf("%lf %lf %lf",&h,&w,&l); frogs.push_back(Frog(h,w,l,i+1)); // We store the list in a vector } sort(frogs.begin(), frogs.end(), Frog()); // We use the built-in sort function with our custom comparator to sort the list // Now we just simply print out the while list for(int i=0;i<frogs.size();i++){ printf("ID:%d H:%.2lf W:%.2lf L:%.2lf\n",frogs[i].i,frogs[i].h,frogs[i].w,frogs[i].l); } return 0; }

**Java Solution**

import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class ZrogTheJudge implements Comparable<ZrogTheJudge>{ // This works as the custom data container for this solution double h,w,l; int i; static final double eps = 0.001; public ZrogTheJudge(double _h, double _w, double _l, int _i){ h = _h; w = _w; l = _l; i = _i; } // The following function is used by the sort function to do comparison // 1 means the 'other' object will go before 'this' // -1 means the 'other' object will go after 'this' @Override public int compareTo(ZrogTheJudge other) { if(this.h<other.h){ return 1; }else if(Math.abs(this.h-other.h)<eps){ if(this.w>other.w){ return 1; }else if(Math.abs(this.w-other.w)<eps){ if(this.l<other.l){ return 1; }else if(Math.abs(this.l-other.l)<eps){ return (this.i<other.i) ? -1:1; } } } return -1; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); ArrayList<ZrogTheJudge> frogs = new ArrayList<ZrogTheJudge>(); for(int i=0;i<n;i++){ frogs.add(new ZrogTheJudge(scan.nextDouble(), scan.nextDouble(), scan.nextDouble(), i+1)); } Collections.sort(frogs); for(int i=0;i<n;i++){ System.out.format("ID:%d H:%.2f W:%.2f L:%.2f\n", frogs.get(i).i,frogs.get(i).h,frogs.get(i).w,frogs.get(i).l); } } }

**Fun fact**: This problem was made for the first Code Knights round. But it keeps getting replaced with other problems. The solution need to represent the number as a binary and loop through the bit from the least significant bit to the most significant bit and count how many times the bit change, assuming that the initial toggle state is the starting bit. This can be done easily with some bitwise operation. Although some participants uses bitset and convert the bitset to string, which also work. Just remember to loop starting from the least significant bit.

**C++ Solution**

#include<iostream> using namespace std; int main() { string init; cin >> init; bool current = init == "ON"; unsigned int num; cin >> num; int count = 0; for(int i=0;i<32;i++){ bool on = (num & (1LL << i)) != 0; if(on != current){ count++; } current = on; } cout << count; }

**Java Solution**

import java.io.PrintStream; import java.util.*; import java.io.*; public class Main{ static Scanner in; static PrintStream out; static PrintStream err; static { in = new Scanner(System.in); out = System.out; err = System.err; boolean enable_debug = false; if(!enable_debug){ err = new PrintStream(new OutputStream(){ public void write(int b){ // NO-OP } }); } } public static <T> void dbg(String s,T val){ err.print(s+": "); err.println(val); } public static void main(String[] args){ String init = in.next(); int num = in.nextInt(); int count = 0; boolean cur = init.equals("ON"); for(int i=0;i<32;i++){ int bit = (1<<i)# boolean on = bit != 0; if(on != cur){ count++; } cur = on; } out.println(count); } }

**Fun fact**: This problem was one of the candidate for the ‘impossible’ problem for IIUM Code Jam 2. But it was not chosen as the other one is hard enough. Personally I think this one harder.

Those who are accustomed to such grid like pattern and the ‘shortest distance’ clue would probably think that this is a BFS (Breath first search) problem. You are correct, but not just any BFS problem because it have the restriction that the Frogs must not collide. To solve this problem, you need to store both of the frog’s position as a state. So it is a state space search problem, which is still basically BFS. But in normal BFS on such ‘grid-like’ problem, the state are usually current position. In this case, it is both position.

The adjacent vertex (or state) are all possible combination of move from the two frog, which are not only up, down, left and right, but also stay. So for each state, there are 25 next state. To detect the collision issue, you need prune the state in which both of the position is the same and the state where the position are swapped from the previous state. Now it become a normal BFS problem which you can get the ‘depth’ of each state. You can store the depth information as a map, but it would be (much) faster if you store it as a four dimensional array.

**C++ Solution**

#include<bits/stdc++.h> using namespace std; typedef pair<int,int> pii; int dr[] = { 0, 1, 0, -1, 0 }; int dc[] = { 1, 0, -1, 0, 0 }; int main(){ int R,C; cin >> R >> C; string grid[R]; for(int i=0;i<R;i++){ cin >> grid[i]; } pii pos1; pii pos2; for(int i=0;i<R;i++){ for(int ic=0;ic<C;ic++){ if(grid[i][ic] == 'A'){ pos1 = make_pair(i,ic); }else if(grid[i][ic] == 'B'){ pos2 = make_pair(i,ic); } } } // Each state is represented by a pair of a pair of integer queue<pair<pii,pii> > queu; map<pair<pii,pii>, int> depth; pair<pii,pii> initial_state = make_pair(pos1, pos2); pair<pii,pii> final_state = make_pair(pos2, pos1); depth[initial_state] = 0; queu.push(initial_state); while(queu.size()){ pair<pii,pii> state = queu.front(); queu.pop(); if(state == final_state){ break; } for(int i=0;i<5;i++){ pii modified_first = make_pair(state.first.first+dr[i], state.first.second+dc[i]); if(modified_first.first >= R || modified_first.first < 0 || modified_first.second >= C || modified_first.second < 0){ continue; } if(grid[modified_first.first][modified_first.second] == 'X'){ continue; } for(int j=0;j<5;j++){ pii modified_second = make_pair(state.second.first+dr[j], state.second.second+dc[j]); if(modified_second.first >= R || modified_second.first < 0 || modified_second.second >= C || modified_second.second < 0){ continue; } if(grid[modified_second.first][modified_second.second] == 'X'){ continue; } if(modified_first == modified_second) continue; // Same place? pair<pii,pii> nstate = make_pair(modified_first, modified_second); if(nstate == make_pair(state.second, state.first)){ // Swapping? continue; } if(depth.find(nstate) != depth.end()){ // Added already continue; } queu.push(nstate); depth[nstate] = depth[state]+1; } } } if(depth.find(final_state) == depth.end()){ cout << -1 << endl; }else{ cout << depth[final_state] << endl; } return 0; }

**Java Solution**

import java.io.PrintStream; import java.util.*; import java.io.*; public class Main{ static Scanner in; static PrintStream out; static PrintStream err; static { in = new Scanner(System.in); out = System.out; err = System.err; boolean enable_debug = true; if(!enable_debug){ err = new PrintStream(new OutputStream(){ public void write(int b){ // NO-OP } }); } } public static <T> void dbg(String s,T val){ err.print(s+": "); err.println(val); } static class State implements Comparable<State>{ public State(){ } public State(State c){ ar = c.ar; ac = c.ac; br = c.br; bc = c.bc; } int ar; int ac; int br; int bc; public int compareTo(State s){ if(ar != s.ar) return ar-s.ar; if(br != s.br) return br-s.br; if(ac != s.ac) return ac-s.ac; return bc-s.bc; } public boolean aSwap(State s){ return s.ar == br && s.br == ar && s.ac == bc && s.bc == ac; } public String toString(){ return "ar"+ar+" ac"+ac+" br"+br+" bc"+bc; } } public static void main(String[] args){ int n = in.nextInt(); int m = in.nextInt(); String gridS[] = new String[n]; for(int i=0;i<n;i++){ gridS[i] = in.next(); } boolean canGo[][] = new boolean[n][m]; State init = new State(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ char c = gridS[i].charAt(j); canGo[i][j] = c!='X'; if(c == 'A'){ init.ar = i; init.ac = j; } if(c == 'B'){ init.br = i; init.bc = j; } } } State finalS = new State(); finalS.ar = init.br; finalS.br = init.ar; finalS.ac = init.bc; finalS.bc = init.ac; int dr[] = { 0, 1, 0, -1, 0 }; int dc[] = { 1, 0, -1, 0, 0 }; TreeMap<State, Integer> depth = new TreeMap<State, Integer>(); Queue<State> que = new LinkedList<State>(); depth.put(init, 0); que.add(init); int answer = -1; //err.println("M is "+m); while(que.size() > 0){ State cur = que.poll(); int cdepth = depth.get(cur); //err.println("cur is "+cur+" depth "+cdepth); if(cur.compareTo(finalS) == 0){ answer = depth.get(cur); //err.println("Break"); break; } for(int i=0;i<5;i++){ State base = new State(cur); base.ar += dr[i]; base.ac += dc[i]; if(base.ar < 0 || base.ar >= n || base.ac < 0 || base.ac >= m) continue; if(!canGo[base.ar][base.ac]) { //err.println("Cannot go"); continue; } for(int i2=0;i2<5;i2++){ State next = new State(base); next.br += dr[i2]; next.bc += dc[i2]; if(next.br < 0 || next.br >= n || next.bc < 0 || next.bc >= m) { continue; } if(!canGo[next.br][next.bc]){ //err.println("Cannot go"); continue; } if(depth.containsKey(next)) continue; if(cur.aSwap(next)) continue; if(cur.ar == cur.br && cur.ac == cur.bc) continue; //err.println("adding "+next); depth.put(next, cdepth+1); que.add(next); } } } out.println(answer); } }

Naughty sister is a math problem and all you need to do is to find the LCM (Least Common Multiple) of two numbers. Calculating LCM with the traditional way could be challenging, time consuming and most probably at the end you would get TLE. But fortunately the Euclidean Algorithm with O(n) can help us to calculate the GCD (for more information check this link http://bit.ly/1jxmUvL) and as (LCM(a,b)*GCD(a,b))= (a*b) you can easily calculate LCM.

**C++ Solution**

#include <iostream> using namespace std; typedef long long ll; ll GCD(ll a, ll b) { //Euclidean Algorithm return b == 0 ? a : GCD(b, a % b); } int main() { ll a,b; cin >> a >> b; while(a && b){ cout << (a*b)/GCD(a,b) << endl; //calculating LCM(a,b) = (a*b)/GCD(a,b) cin >> a >> b; } }

**Java Solution**

import java.util.*; import java.lang.*; import java.io.*; class main { public static long GCD(long a, long b) { //Euclidean Algorithm return b == 0 ? a : GCD(b, a % b); } static Scanner in; static PrintStream out; public static void main (String[] args) throws java.lang.Exception { in = new Scanner(System.in); out = System.out; long a = in.nextInt(); long b = in.nextInt(); while(a > 0 && b > 0){ // check whether they are greater than zero or not out.println((a*b)/GCD(a,b)); //calculating LCM(a,b) = (a*b)/GCD(a,b) a = in.nextInt(); b = in.nextInt(); } } }

This round is particularly hard. I did mention in last round’s analysis that we will be pressured to make hard problems and we did, so this happen. As usual, we all imagine that the difficulty of this round would be just right, but it did not happen. Did I mention that making a balanced round is really hard? Overall, I think it is a good round, but personally, last round was more fun.

Next week (3 September) we will have a special contest, which is not considered a normal round because it can be unfair to some participant and we (the organizer) don’t have to do much work for it. How unfair? Well, I can’t tell you that right now because it would be even more unfair. So stay tune for the next announcement.

The post Code Knights Round 7 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 8 appeared first on IIUM ICPC Team.

]]>This is an announcement for Code Knights Round 8. If this is the first time you heard of **Code Knights**, please checkout this link. The short version is that, we are organizing a competitive programming rounds every two weeks open to all Malaysian university student. We do this for practice, education and mostly for the fun of it.

The competition will be held online, similar with various other competitive programming platform such as codeforces and hackerearth, except the difficulty is tuned down to cater for beginner. You can use C, C++, Python or Java. There will be 5 problem to be solved with varying difficulty.

**Date:** 24th September 2016

**Time:** 8PM to 12 AM Malaysian Time

**Venue:** Online (Link will be given later)

**Registration fees:** * FREE *

**Registration link for DSA students:** https://goo.gl/forms/pecD8HUbhsSAta6B2

**Registration link:** http://goo.gl/forms/VJFvSmekoH2Uox203

**Feedback form:** https://goo.gl/forms/Mm1yGOM3dL8hWY0w1

If you want to participate in Code Knights, please fill up your details in the google forms link above. Register once, and you will be registered for all future rounds. We will remind you on the rounds through emails and whatsapp group. Please register before 6 pm on the day of the competition as I have to input your login information into the system. If you have any question, feel free to comment down below.

The post Code Knights Round 8 appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 6 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>Last Saturday, the 6th round of Code Knights was held, with a total of….. 17 participants. Same as last round, which is also the same as the round before. This round is significantly harder than the last round, which was the easiest round by far.

How hard? Well.. if you compare it to Round 3, its.. *OK-lah*. The winner for this round goes to anas_95 from IIUM, who also won last round. anas_95 was the only participant who manage to solve 4 problems, but he did not solve problem D. It’s nice to see someone from IIUM winning again, but its starting to get boring. Can someone else win next time? stdLn maybe? Heck, I’m even waiting for lim2481284 to make a comeback.

You can find the dataset and PDF through the link below.

Like last time, before you go to the tutorial, please take some moment to fill up our feedback form.

This problem is classified as giveaway problem. In fact the problem is explanatory type of problems where the description of the problem and the solution is provided in the problem statement. Although, the solution is provided in the problem statement, a few of the contestants could not solve it for some reason (They may have thought it is a trap or the name binary search could be scary enough to not want to solve it) or could be other reasons that I do not know. The problem utilizes binary search which is much more faster than linear search. If you try to solve the problem with linear search, you will end up with TLE verdict (Time limit exceeded). Therefore, binary uses [math]log n[/math] operation to quickly find elements in a sorted array.

**C++ Solution**

#include <bits/stdc++.h> using namespace std; #define ABS(x) ((x)<0 ? -(x) : (x)) #define REP(i,n) for(int i=0, _e(n); i<_e; i++) #define FOR(i,a,b) for(int i(a), _e(b); i<=_e; i++) #define FORD(i,a,b) for(int i(a), _e(b); i>=_e; i--) #define FORIT(i, m) for (__typeof((m).begin()) i=(m).begin(); i!=(m).end(); ++i) #define SET(t,v) memset((t), (v), sizeof(t)) #define ALL(x) x.begin(), x.end() #define UNIQUE(c) (c).resize( unique( ALL(c) ) - (c).begin() ) #define inf_int (1<<31)-1 #define inf_long (1<<63)-1 #define sz size() #define pb push_back #define VI vector<int> #define VS vector<string> typedef long long LL; typedef long double LD; typedef pair<int,int> pii; #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x ; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif int main(){ int n, a[2*100000], q, queryValue; int index; cin >> n ; for(int i=0;i<n;i++){ cin >> a[i]; } sort(a,a+n); cin >> q ; for(int i=0;i<q;i++){ cin >> queryValue; index = upper_bound(a,a+n,queryValue) - a; cout << n - index << endl; } return 0; }

**Java Solution**

import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; import java.util.TreeSet; public class Main{ public static void main(String args[]){ Scanner in = new Scanner(System.in); PrintStream out = System.out; int n = in.nextInt(); int[] inputArrays = new int[n]; for(int i=0; i<n ; i++){ inputArrays[i] = in.nextInt(); } Arrays.sort(inputArrays); int q = in.nextInt(); while(q>0){ int query = in.nextInt(); int index = indexOfHigherThanQuery(0,n-1,query,inputArrays); out.println(n - index); q--; } } public static int indexOfHigherThanQuery(int first, int last, int target,int array[]){ int tmp ; int counter, step ; counter = last+1 - first; while(counter>0){ tmp = first ; step = counter/2; tmp = tmp + step ; if ( !(target < array[tmp]) ){ first = ++tmp; counter -= step + 1; } else counter = step ; } return first; } }

The purpose of this problem was to introduce operator overloading and its usage with the built in sort function in both C++ and Java.

The first task is to write the overloading function which needs 3 doubles and 1 int to do the comparison, passing this 3 doubles and 1 int can be done in multiple ways, in this solution we used a custom struct/object to store them together and then sent the struct/object instance as parameter to the overloading function.

Once the function is complete we just need to use the built-in sort function in C++/Java and sort it, time complexity of the built-in sort is O(n*logn), this will work. If you implement a sorting algorithm with O(n*n) time complexity, then it will get Time Limit Exceeded verdict.

Check out the sample solution to further understand how to do operator overloading in C++, Java doesn’t support operator overloading, its a bit different, check the sample Java source code.

**C++ Solution**

#include <bits/stdc++.h> using namespace std; #define eps 0.001 // This is the custom data container for this solution struct Frog{ double h,w,l; // h->height, w->weight, l->length of jump int i; // i-> position in the original list Frog(){} // Empty Constructor, it is needed for sorting using sort function Frog(double _h, double _w, double _l, int _i){ h = _h; w = _w; l = _l; i = _i;} // Constructor for initializing // The following function defines the nature of the operator overloading // In this case the operator is the comparison function, defined by "()" symbol bool operator()(const Frog& a, const Frog& b){ // The follwing conditions decides whether 'a' should go before 'b' or not if(a.h<b.h){ return false; }else if(abs(a.h-b.h)<eps){ if(a.w>b.w){ return false; }else if(abs(a.w-b.w)<eps){ if(a.l<b.l){ return false; }else if(abs(a.l-b.l)<eps){ return a.i<b.i; } } } return true; } }; int main(){ int n; scanf("%d",&n); vector<Frog> frogs; double h,w,l; for(int i=0;i<n;i++){ scanf("%lf %lf %lf",&h,&w,&l); frogs.push_back(Frog(h,w,l,i+1)); // We store the list in a vector } sort(frogs.begin(), frogs.end(), Frog()); // We use the built-in sort function with our custom comparator to sort the list // Now we just simply print out the while list for(int i=0;i<frogs.size();i++){ printf("ID:%d H:%.2lf W:%.2lf L:%.2lf\n",frogs[i].i,frogs[i].h,frogs[i].w,frogs[i].l); } return 0; }

**Java Solution**

import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class ZrogTheJudge implements Comparable<ZrogTheJudge>{ // This works as the custom data container for this solution double h,w,l; int i; static final double eps = 0.001; public ZrogTheJudge(double _h, double _w, double _l, int _i){ h = _h; w = _w; l = _l; i = _i; } // The following function is used by the sort function to do comparison // 1 means the 'other' object will go before 'this' // -1 means the 'other' object will go after 'this' @Override public int compareTo(ZrogTheJudge other) { if(this.h<other.h){ return 1; }else if(Math.abs(this.h-other.h)<eps){ if(this.w>other.w){ return 1; }else if(Math.abs(this.w-other.w)<eps){ if(this.l<other.l){ return 1; }else if(Math.abs(this.l-other.l)<eps){ return (this.i<other.i) ? -1:1; } } } return -1; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); ArrayList<ZrogTheJudge> frogs = new ArrayList<ZrogTheJudge>(); for(int i=0;i<n;i++){ frogs.add(new ZrogTheJudge(scan.nextDouble(), scan.nextDouble(), scan.nextDouble(), i+1)); } Collections.sort(frogs); for(int i=0;i<n;i++){ System.out.format("ID:%d H:%.2f W:%.2f L:%.2f\n", frogs.get(i).i,frogs.get(i).h,frogs.get(i).w,frogs.get(i).l); } } }

**Fun fact**: This problem was made for the first Code Knights round. But it keeps getting replaced with other problems. The solution need to represent the number as a binary and loop through the bit from the least significant bit to the most significant bit and count how many times the bit change, assuming that the initial toggle state is the starting bit. This can be done easily with some bitwise operation. Although some participants uses bitset and convert the bitset to string, which also work. Just remember to loop starting from the least significant bit.

**C++ Solution**

#include<iostream> using namespace std; int main() { string init; cin >> init; bool current = init == "ON"; unsigned int num; cin >> num; int count = 0; for(int i=0;i<32;i++){ bool on = (num & (1LL << i)) != 0; if(on != current){ count++; } current = on; } cout << count; }

**Java Solution**

import java.io.PrintStream; import java.util.*; import java.io.*; public class Main{ static Scanner in; static PrintStream out; static PrintStream err; static { in = new Scanner(System.in); out = System.out; err = System.err; boolean enable_debug = false; if(!enable_debug){ err = new PrintStream(new OutputStream(){ public void write(int b){ // NO-OP } }); } } public static <T> void dbg(String s,T val){ err.print(s+": "); err.println(val); } public static void main(String[] args){ String init = in.next(); int num = in.nextInt(); int count = 0; boolean cur = init.equals("ON"); for(int i=0;i<32;i++){ int bit = (1<<i)# boolean on = bit != 0; if(on != cur){ count++; } cur = on; } out.println(count); } }

**Fun fact**: This problem was one of the candidate for the ‘impossible’ problem for IIUM Code Jam 2. But it was not chosen as the other one is hard enough. Personally I think this one harder.

Those who are accustomed to such grid like pattern and the ‘shortest distance’ clue would probably think that this is a BFS (Breath first search) problem. You are correct, but not just any BFS problem because it have the restriction that the Frogs must not collide. To solve this problem, you need to store both of the frog’s position as a state. So it is a state space search problem, which is still basically BFS. But in normal BFS on such ‘grid-like’ problem, the state are usually current position. In this case, it is both position.

The adjacent vertex (or state) are all possible combination of move from the two frog, which are not only up, down, left and right, but also stay. So for each state, there are 25 next state. To detect the collision issue, you need prune the state in which both of the position is the same and the state where the position are swapped from the previous state. Now it become a normal BFS problem which you can get the ‘depth’ of each state. You can store the depth information as a map, but it would be (much) faster if you store it as a four dimensional array.

**C++ Solution**

#include<bits/stdc++.h> using namespace std; typedef pair<int,int> pii; int dr[] = { 0, 1, 0, -1, 0 }; int dc[] = { 1, 0, -1, 0, 0 }; int main(){ int R,C; cin >> R >> C; string grid[R]; for(int i=0;i<R;i++){ cin >> grid[i]; } pii pos1; pii pos2; for(int i=0;i<R;i++){ for(int ic=0;ic<C;ic++){ if(grid[i][ic] == 'A'){ pos1 = make_pair(i,ic); }else if(grid[i][ic] == 'B'){ pos2 = make_pair(i,ic); } } } // Each state is represented by a pair of a pair of integer queue<pair<pii,pii> > queu; map<pair<pii,pii>, int> depth; pair<pii,pii> initial_state = make_pair(pos1, pos2); pair<pii,pii> final_state = make_pair(pos2, pos1); depth[initial_state] = 0; queu.push(initial_state); while(queu.size()){ pair<pii,pii> state = queu.front(); queu.pop(); if(state == final_state){ break; } for(int i=0;i<5;i++){ pii modified_first = make_pair(state.first.first+dr[i], state.first.second+dc[i]); if(modified_first.first >= R || modified_first.first < 0 || modified_first.second >= C || modified_first.second < 0){ continue; } if(grid[modified_first.first][modified_first.second] == 'X'){ continue; } for(int j=0;j<5;j++){ pii modified_second = make_pair(state.second.first+dr[j], state.second.second+dc[j]); if(modified_second.first >= R || modified_second.first < 0 || modified_second.second >= C || modified_second.second < 0){ continue; } if(grid[modified_second.first][modified_second.second] == 'X'){ continue; } if(modified_first == modified_second) continue; // Same place? pair<pii,pii> nstate = make_pair(modified_first, modified_second); if(nstate == make_pair(state.second, state.first)){ // Swapping? continue; } if(depth.find(nstate) != depth.end()){ // Added already continue; } queu.push(nstate); depth[nstate] = depth[state]+1; } } } if(depth.find(final_state) == depth.end()){ cout << -1 << endl; }else{ cout << depth[final_state] << endl; } return 0; }

**Java Solution**

import java.io.PrintStream; import java.util.*; import java.io.*; public class Main{ static Scanner in; static PrintStream out; static PrintStream err; static { in = new Scanner(System.in); out = System.out; err = System.err; boolean enable_debug = true; if(!enable_debug){ err = new PrintStream(new OutputStream(){ public void write(int b){ // NO-OP } }); } } public static <T> void dbg(String s,T val){ err.print(s+": "); err.println(val); } static class State implements Comparable<State>{ public State(){ } public State(State c){ ar = c.ar; ac = c.ac; br = c.br; bc = c.bc; } int ar; int ac; int br; int bc; public int compareTo(State s){ if(ar != s.ar) return ar-s.ar; if(br != s.br) return br-s.br; if(ac != s.ac) return ac-s.ac; return bc-s.bc; } public boolean aSwap(State s){ return s.ar == br && s.br == ar && s.ac == bc && s.bc == ac; } public String toString(){ return "ar"+ar+" ac"+ac+" br"+br+" bc"+bc; } } public static void main(String[] args){ int n = in.nextInt(); int m = in.nextInt(); String gridS[] = new String[n]; for(int i=0;i<n;i++){ gridS[i] = in.next(); } boolean canGo[][] = new boolean[n][m]; State init = new State(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ char c = gridS[i].charAt(j); canGo[i][j] = c!='X'; if(c == 'A'){ init.ar = i; init.ac = j; } if(c == 'B'){ init.br = i; init.bc = j; } } } State finalS = new State(); finalS.ar = init.br; finalS.br = init.ar; finalS.ac = init.bc; finalS.bc = init.ac; int dr[] = { 0, 1, 0, -1, 0 }; int dc[] = { 1, 0, -1, 0, 0 }; TreeMap<State, Integer> depth = new TreeMap<State, Integer>(); Queue<State> que = new LinkedList<State>(); depth.put(init, 0); que.add(init); int answer = -1; //err.println("M is "+m); while(que.size() > 0){ State cur = que.poll(); int cdepth = depth.get(cur); //err.println("cur is "+cur+" depth "+cdepth); if(cur.compareTo(finalS) == 0){ answer = depth.get(cur); //err.println("Break"); break; } for(int i=0;i<5;i++){ State base = new State(cur); base.ar += dr[i]; base.ac += dc[i]; if(base.ar < 0 || base.ar >= n || base.ac < 0 || base.ac >= m) continue; if(!canGo[base.ar][base.ac]) { //err.println("Cannot go"); continue; } for(int i2=0;i2<5;i2++){ State next = new State(base); next.br += dr[i2]; next.bc += dc[i2]; if(next.br < 0 || next.br >= n || next.bc < 0 || next.bc >= m) { continue; } if(!canGo[next.br][next.bc]){ //err.println("Cannot go"); continue; } if(depth.containsKey(next)) continue; if(cur.aSwap(next)) continue; if(cur.ar == cur.br && cur.ac == cur.bc) continue; //err.println("adding "+next); depth.put(next, cdepth+1); que.add(next); } } } out.println(answer); } }

Naughty sister is a math problem and all you need to do is to find the LCM (Least Common Multiple) of two numbers. Calculating LCM with the traditional way could be challenging, time consuming and most probably at the end you would get TLE. But fortunately the Euclidean Algorithm with O(n) can help us to calculate the GCD (for more information check this link http://bit.ly/1jxmUvL) and as (LCM(a,b)*GCD(a,b))= (a*b) you can easily calculate LCM.

**C++ Solution**

#include <iostream> using namespace std; typedef long long ll; ll GCD(ll a, ll b) { //Euclidean Algorithm return b == 0 ? a : GCD(b, a % b); } int main() { ll a,b; cin >> a >> b; while(a && b){ cout << (a*b)/GCD(a,b) << endl; //calculating LCM(a,b) = (a*b)/GCD(a,b) cin >> a >> b; } }

**Java Solution**

import java.util.*; import java.lang.*; import java.io.*; class main { public static long GCD(long a, long b) { //Euclidean Algorithm return b == 0 ? a : GCD(b, a % b); } static Scanner in; static PrintStream out; public static void main (String[] args) throws java.lang.Exception { in = new Scanner(System.in); out = System.out; long a = in.nextInt(); long b = in.nextInt(); while(a > 0 && b > 0){ // check whether they are greater than zero or not out.println((a*b)/GCD(a,b)); //calculating LCM(a,b) = (a*b)/GCD(a,b) a = in.nextInt(); b = in.nextInt(); } } }

This round is particularly hard. I did mention in last round’s analysis that we will be pressured to make hard problems and we did, so this happen. As usual, we all imagine that the difficulty of this round would be just right, but it did not happen. Did I mention that making a balanced round is really hard? Overall, I think it is a good round, but personally, last round was more fun.

Next week (3 September) we will have a special contest, which is not considered a normal round because it can be unfair to some participant and we (the organizer) don’t have to do much work for it. How unfair? Well, I can’t tell you that right now because it would be even more unfair. So stay tune for the next announcement.

The post Code Knights Round 6 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 6 appeared first on IIUM ICPC Team.

]]>This is an announcement for Code Knights Round 6. In previous round, 17 participant from 7 Malaysian university participated in this competitive programming competition. The winner goes to “anas_95” from IIUM. If this is the first time you heard of Code Knights, please checkout this link. The short version is that, we are organizing a competitive programming rounds every two weeks open to all Malaysian university student. We do this for practice, education and mostly for the fun of it.

**Date:** 27th August 2016

**Time:** 8PM to 12 AM

**Venue:** Online (Link will be given later)

**Registration fees:** * FREE *

**Registration link:** http://goo.gl/forms/VJFvSmekoH2Uox203

**Feedback form:** https://goo.gl/forms/Mm1yGOM3dL8hWY0w1

The post Code Knights Round 6 appeared first on IIUM ICPC Team.

]]>The post Code Knights Round 5 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>Last saturday, Code Knights Round 5 was held with a total of 17 participant… which is pretty much the same with round 4. The winner (finally…) goes to anas_95 from IIUM by the virtue of answering all problems faster with less penalty (which is 0). This round is (unfortunately) the easiest round ever with 6 participant answering all problems.

The second place goes to UncleWong from UM and the third place goes to joscmw95 from UTAR. foreveralone, winner of round 4 is at the fourth place. Notable mention includes two time winner lim2481284 from UNITEN which continues his effort of not even trying. You can find the dataset and pdf through the link below:

Before we go to the answers, we would be grateful if you could answer a short 5 minute feedback form about Code Knights. Your feedback will go a long way to improve Code Knights.

The solution is very aladeen. The naive way will also work which is of time complexity [math]O(n * m)[/math] for the given [math]n[/math] and [math]m[/math] , here [math]n \leq 300[/math] and [math]m \leq 1000[/math] .

In the naive way we store all the words in an array, and then later for each query word we check the array linearly for a match.

A smarter way is to use the Map data structure which is built-in in C++ and Java(TreeMap). The time complexity then becomes [math]O(n logn)[/math], then for each query word the search will be done in the map, as the map is actually an AVL tree, it will take only [math]logn[/math] time to find a particular key.

**C++ Solution**

#include <bits/stdc++.h> using namespace std; int main(){ map<string, string> dict; int n,m; string word; cin>>n; for(int i=0;i<n;i++){ cin>>word; dict[word] = "Aladeen"; } cin>>m; for(int i=0;i<m;i++){ cin>>word; if(dict.find(word)==dict.end()) cout<<word<<endl; else cout<<dict[word]<<endl; } return 0; }

**Java Solution**

import java.util.Scanner; import java.util.TreeMap; public class AladeenOrAladeen { public static void main(String[] args) { TreeMap<String, String> dict = new TreeMap<String, String>(); int n,m; String word; Scanner scan = new Scanner(System.in); n = scan.nextInt(); for(int i=0;i<n;i++){ word = scan.next(); dict.put(word, "Aladeen"); } m = scan.nextInt(); for(int i=0;i<m;i++){ word = scan.next(); if(dict.containsKey(word)){ System.out.println(dict.get(word)); }else{ System.out.println(word); } } } }

This problem is meant to be the giveway problem. It is straight forward. you are given inputs and all formulas and you just need to apply them.

**C++ Solution**

#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main(){ int T,a,b; cin >> T; for(int i=0;i<T;i++){ cin >> a >> b ; cout << fixed << setprecision(2) << (a*b/2.0) << "," << sqrt(a*a+b*b) << endl; } return 0; }

This problem is a simple implementation you just need to do as the problem said. Basically you just need to add up the calories he eats during the day and if he passes the limited keep track of the foods that causes him passing the limit. The one to keep in mind is that we should consider that he doesn’t eat the foods causing him passing the limit so the calories of those should not be added to his calories intake of the day. And finally if he did not pass his limit by overeating you need to make sure that he did not eat less than calories required so you basically need to get the difference of the calories intake and minimum calories required.

**C++ Solution**

#include <iostream> #include <string> using namespace std; int main(){ int n, max, min, count = 0; cin >> n; cin >> min >> max; while (n--){ int m, sum = 0, calories; bool overeat = false; string name, output = "Perfect day! Good job."; cin >> m; while(m--){ cin >> name >> calories; if((sum + calories) > max){ if(overeat){ output += (" " + name); } else{ overeat = true; output = "Slow down dude! You should not eat: " + name; } } else{ sum += calories; } } if(sum < min && !overeat){ output = "Good day but not enough. Eat at least " + to_string(min - sum) + " more calories."; } cout << "Day " << ++count <<": " << output << endl; } }

**Java Solution**

import java.io.PrintStream; import java.util.*; import java.io.*; public class Main2{ static Scanner in; static PrintStream out; static PrintStream err; static { in = new Scanner(System.in); out = System.out; err = System.err; boolean enable_debug = true; if(!enable_debug){ err = new PrintStream(new OutputStream(){ public void write(int b){ // NO-OP } }); } } public static <T> void dbg(String s,T val){ err.print(s+": "); err.println(val); } static int min; static int max; public static void solve(int day){ int m = in.nextInt(); int current = 0; ArrayList<String> shouldNot = new ArrayList<String>(); for(int i=0;i<m;i++){ String s = in.next(); int food = in.nextInt(); int nextCurrent = current+food; if(nextCurrent > max){ shouldNot.add(s); }else{ current = nextCurrent; } } out.print("Day "+day+": "); if(current < min){ out.println("Good day but not enough. Eat at least "+(min-current)+" more calories."); }else if(shouldNot.size() > 0){ out.print("Slow down dude! You shouldn’t eat:"); for(String s:shouldNot){ out.print(" "+s); } out.println(); }else{ out.println("Perfect day! Good job."); } } public static void main(String[] args){ int n = in.nextInt(); min = in.nextInt(); max = in.nextInt(); for(int i=0;i<n;i++){ solve(i+1); } } }

There are multiple way to check if the hexagon fit the criteria. Among other includes rotate each point by 120 degree and compare the last point. But one of the simplest one is this, for each two consecutive side, the sum of the length of the two side must be equal to the sum of the length of the opposite two side. Formally, [math]$a_{i \% 6} + a_{(i+1) \% 6} = a_{(i+3) \% 6} + a_{(i+4) \% 6}$[/math] for all [math]$i$[/math]. So checking that for three consecutive [math]$i$[/math] should be enough.

**C++ Solution**

#include<iostream> #include<vector> #include<utility> using namespace std; int main(){ int sides[6]; for(int i=0;i<6;i++){ cin >> sides[i]; } bool ok = true; for(int i=0;i<3;i++){ int cside = sides[i]+sides[i+1]; int oside = sides[(i+3)%6]+sides[(i+4)%6]; if(cside != oside){ ok = false; } } if(ok){ cout << "Triangleable Hexagon" << endl; }else{ cout << "Ugly Hexagon" << endl; } return 0; }

There are different methods to solve this problem. This problem is also our first problems that can have multiple output. That means, the output for a specific input could vary from one solution to another.

Example:

# Input: 4 3 -6 7 0 # output: (One possible answer) 1 -6 2 3 7 1 0 # output: (Another possible answer) 2 -6 3 1 7 1 0

All these outputs are correct as long as you meet the conditions in the problem description.

Our solution to this problem is to have the inputs sorted in ascending order. Then append the first element in the sorted array to the first set (The product of this set is negative), then check if the last element in the sorted array is zero then we need to append the second and third element to the second set. (when the last element in the sorted array is zero means that we do not have any postive integer in the set and therefore we need to push two negative numbers the second set in order to make the product positive). Now if the last element is not zero then push the last element to the second set.

The third set would include all other numbers including zero to make the product equal to zero.

**C++ Solution**

#include <bits/stdc++.h> using namespace std; #define ABS(x) ((x)<0 ? -(x) : (x)) #define REP(i,n) for(int i=0, _e(n); i<_e; i++) #define FOR(i,a,b) for(int i(a), _e(b); i<=_e; i++) #define FORD(i,a,b) for(int i(a), _e(b); i>=_e; i--) #define FORIT(i, m) for (__typeof((m).begin()) i=(m).begin(); i!=(m).end(); ++i) #define SET(t,v) memset((t), (v), sizeof(t)) #define ALL(x) x.begin(), x.end() #define UNIQUE(c) (c).resize( unique( ALL(c) ) - (c).begin() ) #define inf_int (1<<31)-1 #define inf_long (1<<63)-1 #define sz size() #define pb push_back #define VI vector<int> #define VS vector<string> typedef long long LL; typedef long double LD; typedef pair<int,int> pii; #ifdef DEBUG #define dbg(x) x #define dbgp(x) cerr << x ; #else #define dbg(x) //x #define dbgp(x) //cerr << x << endl; #endif int n , a[100] ; int main(){ cin >> n ; REP(i,n){ cin >> a[i]; } sort(a,a+n); cout << 1 << " " << a[0] << endl; if ( a[n-1] == 0 ) { cout << 2 << " " << a[1] << " " << a[2] << endl; cout << n-3 ; for(int i=3;i<n;i++) cout << " " << a[i]; cout << endl; } else { cout << 1 << " " << a[n-1] << endl; cout << n-2 ; for(int i=1;i<n-1;i++) cout << " " << a[i]; cout << endl; } return 0; }

**Java Solution**

import java.io.PrintStream; import java.util.*; import java.io.*; public class Main{ static Scanner in; static PrintStream out; static PrintStream err; static { in = new Scanner(System.in); out = System.out; err = System.err; boolean enable_debug = true; if(!enable_debug){ err = new PrintStream(new OutputStream(){ public void write(int b){ // NO-OP } }); } } public static <T> void dbg(String s,T val){ err.print(s+": "); err.println(val); } public static void main(String[] args){ int n = in.nextInt(); ArrayList<Integer> negatives = new ArrayList<Integer>(); ArrayList<Integer> positives = new ArrayList<Integer>(); ArrayList<Integer> zeroes = new ArrayList<Integer>(); for(int i=0;i<n;i++){ int d = in.nextInt(); if(d == 0){ zeroes.add(0); }else if(d < 0){ negatives.add(d); }else{ positives.add(d); } } if(positives.size() == 0){ int removed1 = negatives.remove(negatives.size()-1); int removed2 = negatives.remove(negatives.size()-1); positives.add(removed1); positives.add(removed2); } if(negatives.size()%2 == 0){ int removed1 = negatives.remove(negatives.size()-1); zeroes.add(removed1); } out.print(negatives.size()); for(int d: negatives){ out.print(" "+d); } out.println(); out.print(positives.size()); for(int d: positives){ out.print(" "+d); } out.println(); out.print(zeroes.size()); for(int d: zeroes){ out.print(" "+d); } out.println(); } }

For the first time ever in Code Knights history, the number of participant did not increase. Well… that was depressing. Have we reached our plateau? Regardless with how many participant, we will still continue. Next round, you can bet that we have been pressured by this round to create a much harder problem. Will the problem setter exercise some restraint? Find out on the next round.

*The narrator don’t have much medieval remark idea anymore. It kinda feels strange because in Code Knights, one person’s win does not necessarily mean another person’s loss, which is unlike actual physical battle, with swords and such. Anyway… just imagine I said something fancy with the following content: UncleWong answer all first, followed by anas_95 which overtook him because UncleWong have 5 wrong submission at that time. stdLn also answered all problems without any wrong submission, but he came late. lim2481284 have two wrong submission for problem A because of a typo. And he did not manage to solve D. Shahril is MIA for 2 round now… Where is him?*

The post Code Knights Round 5 Results and Problem Analysis appeared first on IIUM ICPC Team.

]]>