Sunday, June 10, 2007

Penyisihan Indonesia National Contest 2007

Babak Penyisihan, 10 Juni 2007

Hallo para peserta/mahasiswa/i atau siapapun yang tertarik untuk melihat soal-soal beserta pembahasan lomba Bina Nusantara Programming Contest 2007 (BNPCCS 2007) yang sekarang berubah nama menjadi Indonesia National Contest (INC 2007).

Saya tahun ini tidak eligible untuk ikut lomba tersebut, tetapi saya tetap antusias dengan perkembangan lomba programming. Senang sekali bisa ikut penyisihan INC 2007 sebagai peserta bayangan (terima kasih kepada tim juri yang membuatkan ID bayangan). FYI, peserta bayangan tugasnya hanya membayang-bayangi peserta lainnya :) tetapi tidak mendapat hadiah apapun kalo menang (note: tidak sembarang orang bisa mendaftar menjadi peserta bayangan).

Ok cukup basa-basinya, berikut adalah 5 soal dikeluarkan untuk babak penyisihan berikut pembahasannya dan code solusi saya:

Nama Soal Pembuat Soal Pembahasan Solusi
A The Chosen Sub Matrix Bong Win Ce Brute Force
B Avoiding Financial Nightmare Bong Win Ce Binary Search
C No Pause Telegraph Bong Win Ce Greedy
D Burger, French Fries, Soft Drink Suhendry Effendy Combinatorics
E Taxi! Suhendry Effendy Dynamic Programming

Kalau menurut saya, tingkat kesulitan diurutkan dari paling gampang ke paling susah adalah: C, A, D, B, E.

Di babak final nanti saya akan terbang ke Indo untuk ikut membayang-bayangi NoMoreAC! (satu satunya tim yang menyapu bersih soal penyisihan dan mendapatkan keadaan dimana "No More AC").

Penyisihan Indonesia National Contest 2007 :: Problem E - Taxi!

ACM/ICPC Indonesia National Contest 2007 - Qualification

Problem E

Taxi!

Time Limit: 1s


Taxi Driver:  "Where to go, sir?"
Passenger:  "Kemanggisan, Binus Campus, please."
Taxi Driver:  "Okay, and which way to go?"
Passenger:  "Just take the fastest one."

This kind of conversation usually happens when we take a taxi. Many people think that the fastest way would mean the cheapest one as well. But it's not always true! Sometimes the fastest way could be more expensive than the slower one and vice versa, some factors are: toll fee, longer road without traffic jam, etc.

We will model this kind of situation on this problem. The city has n intersections and m bidirectional roads connecting pairs of intersections. Each road will cost you a certain time and money (taxi fare). Write a program to find the minimum time to take you to your destination however the travel expenses must not exceed your money.


Input Specification

The first line of each case contains two integers, n (1 <= n <= 100) intersections and m roads. The intersections are numbered from 0 to n-1. The next m lines will each contains four integers: u, v, t, and c (1 <= t,c <= 100), means that there is a road from intersection u to intersection v and vice versa which will cost you t minute(s) and c Rupiah(s). The last line of each case will contains three integers: s, d, and r (1 <= r <= 100), means that you want to go to d (your destination point) from s (your starting point) while you only have r Rupiah(s).


Output Specification

For each case, output in a single line the minimum time to reach your destination while the total cost doesn't exceed your money.


Sample Input

3 3
0 2 16 19
0 1 9 12
1 2 5 13
0 2 20
4 5
0 1 2 11 
1 2 7 27
2 3 4 10
0 3 6 25
3 1 5 12
0 2 35

Sample Output

16
10


Problem Setter: Suhendry Effendy


Pembahasan Problem E - Taxi!

Diberikan N persimpangan dan M jalan yang menghubungkannya. Anda ingin berpergian dari persimpangan A ke persimpangan B, tetapi anda hanya mempunyai uang sebanyak R rupiah. Setiap M jalan yang menghubungkan 2 persimpangan, tercatat harga dan waktu untuk melewati jalan tersebut (arahnya tidak masalah). Anda tidak peduli uang anda habis terpakai semua atau tersisa (tetapi tidak boleh negative!), anda hanya peduli waktu tercepat yang mungkin dari A ke B menggunakan uang R rupiah. Berapakah waktu tercepat tersebut?

Ini adalah soal tersulit di babak penyisihan. Karena untuk menyelesaikannya, anda setidaknya harus bisa rekursi + memo (dp topdown) atau A* complete search. Dijkstra yang hanya berdasarkan waktu tidak mempan disini karena ada kasus dimana waktu tercepat membutuhkan uang melebihi R rupiah, jadi anda harus memilih waktu ke-2 atau ke-3 tercepat, dst.. sampai waktu ke-x tercepat dimana hanya membutuhkan uang kurang atau sama dengan R rupiah.

Dynamic Programming dengan topdown approach (rekursi + memo) merupakan cara paling gampang untuk menyelesaikan problem ini. State dari Dynamic Programmingnya adalah fastest[P][U], artinya: berapa waktu tercepat untuk sampai ke tujuan dari posisi P, dengan sisa uang U. Jika anda bisa mengisi semua tabel ini, maka jawabannya adalah fastest[A][R]. Cara mengisi tabel tersebut, bisa menggunakan rekursi. Untuk lebih jelasnya, lihat source code taxi-dp-topdown.c dibawah.

A* adalah suatu cara pencarian yang komplit (complete search), artinya semua possibility akan dipertimbangkan. Kelemahannya adalah state space nya akan meluas dengan cepat (boros memory) dan agak lambat sedikit (ada faktor log(n) dari priority queue sewaktu insert ataupun extractMin). Tetapi A* akan sangat cepat jika solusinya selalu ada dan heuristic yang dipakai bagus.

Untuk problem ini, A* nya bisa dilakukan dengan meng-generate semua possible paths, dan menjalankan terlebih dahulu jalan yang paling murah. Untungnya, di problem ini A* nya bisa dibantu dengan sedikit "memo" sehingga bisa berjalan cepat. Memo nya adalah jangan memproses lagi path yang melalui suatu persimpangan yang time nya lebih besar dari sebelumnya. A* ini akan berjalan sekitar O(N^2). Memo ini akan berhasil karena jika ada path lain yang mengunjungi node yang sudah pernah dikunjungi, berarti costnya sekarang lebih mahal (karena A* selalu memproses yang costnya murah dahulu). Kalau cost sekarang lebih mahal, kita tinggal lihat apakah waktu sekarang lebih cepat? kalau tidak lebih cepat, maka tidak perlu lagi dilanjutkan (akan selalu rugi).

Yang membuat soal ini agak susah adalah, anda harus membuat Priority Queue data structure sendiri untuk mengimplementasinya jika tidak mau maka anda harus menguasai STL priority_queue di C++. Soal ini bukan soal mudah :) Saya sertakan kode A* dengan Priority Queue bikinan sendiri (yang lebih lambat, versi O(N)) dan kode A* dengan STL priority_queue (yang lebih cepat, O(log(N))).

Solusi Java untuk A* mungkin lebih mudah dimengerti daripada versi C/C++ karena Java 5 juga support Priority Queue

Note: A* diatas tidak ada heuristic functionnya, jadi bisa dibilang A* degenerate menjadi Dijkstra biasa.

#include <stdio.h>
#include <string.h>

int n,A,B,inf=1000000000;
int waktu[100][100];
int harga[100][100];
int memo[100][101];

int fastest(int P, int R){
    int i, ret = inf;
    if (P==B) return 0;
    if (memo[P][R]!=-1) return memo[P][R];

    for (i=0; i<n; i++){
        if (waktu[P][i]!=-1 && R>=harga[P][i]){
            int t = waktu[P][i] + fastest(i,R-harga[P][i]);
            if (t < ret) ret = t;
        }
    }
    return memo[P][R] = ret;
}

int main(){
    int m,u,v,t,c,i,R;
    
    while (scanf("%d %d",&n,&m)!=EOF){
        memset(waktu,-1,sizeof(waktu));
        memset(harga,-1,sizeof(harga));
        for (i=0; i<m; i++){
            scanf("%d %d %d %d",&u,&v,&t,&c);
            waktu[u][v] = waktu[v][u] = t;
            harga[u][v] = harga[v][u] = c;
        }
        scanf("%d %d %d",&A,&B,&R);
        memset(memo,-1,sizeof(memo));
        printf("%d\n",fastest(A,R));
    }
}
#include <stdio.h>
#include <stdlib.h>

#define MAXN 105
#define INF 1000000

typedef struct {
    int harga, waktu, pos;
} Node;

int nodecmp(const void *a, const void *b){
    Node *na = (Node*) a;
    Node *nb = (Node*) b;
    return na->harga - nb->harga;
}

Node pq[100000];
int harga[MAXN][MAXN];
int waktu[MAXN][MAXN];
int bestTime[MAXN];

int main(){
    int n,m,u,v,t,c,duit,i,pqSize;

    while (scanf("%d %d",&n,&m)!=EOF){
        for (u=0; u<n; u++){
            for (v=0; v<n; v++) waktu[u][v] = -1;
            bestTime[u] = INF;
        }

        for (i=0; i<m; i++){
            scanf("%d %d %d %d",&u,&v,&t,&c);
            waktu[u][v] = waktu[v][u] = t;
            harga[u][v] = harga[v][u] = c;
        }
        scanf("%d %d %d",&u,&v,&duit);

        pq[0] = (Node){0,0,u};
        pqSize = 1;
        while (pqSize > 0){
            qsort(pq,pqSize,sizeof(Node),nodecmp); // sort berdasarkan harga termurah
            Node node = pq[0];
            pq[0] = pq[--pqSize]; // timpa elemen pertama dengan terakhir

            if (bestTime[node.pos] <= node.waktu) continue;
            bestTime[node.pos] = node.waktu;
            if (node.pos == v) continue;

            for (i=0; i<n; i++) {
                if (waktu[node.pos][i]==-1) continue;
                if (node.harga + harga[node.pos][i] > duit) continue;
                pq[pqSize++] = (Node){
                    node.harga + harga[node.pos][i],
                    node.waktu + waktu[node.pos][i],
                    i
                };
            }
        }
        
        printf("%d\n",bestTime[v]);
    }
}
#include <stdio.h>
#include <queue>

using namespace std;

#define MAXN 105
#define INF 1000000

typedef struct Node {
    int harga, waktu, pos;

    bool operator<(Node const &that) const {
        return harga > that.harga;
    }
} Node;

int harga[MAXN][MAXN];
int waktu[MAXN][MAXN];
int bestTime[MAXN];

int main(){
    int n,m,u,v,t,c,duit,i;

    while (scanf("%d %d",&n,&m)!=EOF){
        for (u=0; u<n; u++){
            for (v=0; v<n; v++) waktu[u][v] = -1;
            bestTime[u] = INF;
        }

        for (i=0; i<m; i++){
            scanf("%d %d %d %d",&u,&v,&t,&c);
            waktu[u][v] = waktu[v][u] = t;
            harga[u][v] = harga[v][u] = c;
        }
        scanf("%d %d %d",&u,&v,&duit);

        priority_queue<Node> pq;
        pq.push((Node){0,0,u});
        while (!pq.empty()){
            Node node = pq.top(); pq.pop();

            if (bestTime[node.pos] <= node.waktu) continue;
            bestTime[node.pos] = node.waktu;
            if (node.pos == v) continue;

            for (i=0; i<n; i++) {
                if (waktu[node.pos][i]==-1) continue;
                if (node.harga + harga[node.pos][i] > duit) continue;
                pq.push((Node){
                    node.harga + harga[node.pos][i],
                    node.waktu + waktu[node.pos][i],
                    i
                });
            }
        }
        
        printf("%d\n",bestTime[v]);
    }
}
import java.util.*;

public class TaxiAStar {
    class Node implements Comparable<Node> {
        int harga, waktu, pos;

        public Node(int harga, int waktu, int pos){
            this.harga = harga;
            this.waktu = waktu;
            this.pos = pos;
        }

        public int compareTo(Node that){
            return this.harga - that.harga;
        }
    }

    int[][] harga;
    int[][] waktu;
    int[] bestTime;

    public void solve(){
        Scanner scan = new Scanner(System.in);

        while (scan.hasNextInt()){
            int N = scan.nextInt();
            int M = scan.nextInt();

            harga = new int[N][N];
            waktu = new int[N][N];
            bestTime = new int[N];

            for (int i=0; i<N; i++){
                for (int j=0; j<N; j++)
                    waktu[i][j] = -1;
                bestTime[i] = 1000000000;
            }

            for (int i=0; i<M; i++){
                int u = scan.nextInt();
                int v = scan.nextInt();
                int t = scan.nextInt();
                int c = scan.nextInt();
                waktu[u][v] = waktu[v][u] = t;
                harga[u][v] = harga[v][u] = c;
            }

            int A = scan.nextInt();
            int B = scan.nextInt();
            int R = scan.nextInt();

            PriorityQueue<Node> pq = new PriorityQueue<Node>();
            pq.offer(new Node(0,0,A));
            while (pq.size()>0){
                Node node = pq.poll();

                if (bestTime[node.pos] <= node.waktu) continue;
                bestTime[node.pos] = node.waktu;
                if (node.pos == B) continue;

                for (int i=0; i<N; i++){
                    if (waktu[node.pos][i]==-1) continue;
                    if (node.harga + harga[node.pos][i] > R) continue;
                    pq.offer(new Node(
                        node.harga + harga[node.pos][i],
                        node.waktu + waktu[node.pos][i],
                        i
                    ));
                }
            }
            
            System.out.printf("%d\n",bestTime[B]);
        }

        scan.close();
    }

    public static void main(String[] args){
        new TaxiAStar().solve();
    }
}

Back to Home

Penyisihan Indonesia National Contest 2007 :: Problem D - Burger, French Fries, Soft Drink

ACM/ICPC Indonesia National Contest 2007 - Qualification

Problem D

Burger, French Fries, Soft Drink

Time Limit: 1s


Anna works as a waitress at a popular fast-food restaurant in Indonesia, "Om Burger". Her job is much easier than any waiters/waitresses at other fast-food restaurants, because Om Burger owns an automatic fast-food machine.

Om Burger serves only a single combo-menu package named Paket Uenak, which consists of three items: 1 Burger (B), 1 French Fries (F), and 1 Soft Drink (S). Each customer would be given a card to write the number of Paket Uenak packages to be ordered. The card should be given back to Anna who will insert it into the machine. The machine will prepare all items of each package one by one according to the written number on the card, but not necessary in any particular order of item. For example, if the number 2 (means 2 Paket Uenak packages are ordered by a customer) is written on the card, the machine will prepare items in the sequence of BBFFSS, or any of its permutation (BFSBFS, BBFSFS, etc). There could be more than one card to be processed by the machine at a time. However the machine will process all cards sequentially. That means it will not proceed to the next card before finishing the current card.

One day, some customers are queuing to put their orders. While they make a quite long queue, it gives Anna an idea. Instead of inserting the card one by one, she initiatively inserts more than one card at a time. Brilliant, isn't she? Well, let's see what happens next. The machine does work well, but now she doesn't have any idea which item belongs to which card, because the machine doesn't give any separations to separate packages from different cards.

Fortunately, Anna still remembers the number of cards inserted and its sequence (which card belongs to whom). However, she doesn't remember the number of Paket Uenak packages written on each card.

For example, if there are two cards inserted into the machine:
Prepared : B B F S S F S F B B F S
Possibility-1 : (B B F S S F) ( S F B B F S), the first customer ordered 2 Paket Uenak packages, and the second customer ordered 2 Paket Uenak packages.
Possibility-2 : (B B F S S F S F B) (B F S), the first customer ordered 3 Paket Uenak packages, and the second customer ordered 1 Paket Uenak package.

No need to tell, that now she's apologizing and questioning all customers for what they have been ordering again. But this problem has aroused her curiosity as she is also a student in Computer Science. Help Anna to find how many possible order arrangements could be found from any given condition(s).


Input Specification

Each line of input contains an integer N (1 < N < 30) denoting the number of card(s) inserted, and a string which contains character(s) of B, F, and S (no spaces) denoting the order of items prepared by the machine. You may assume that the length of each string is less than 100.


Output Specification

For each line of input, print the number of possible order arrangements could be found. If there is no possible order arrangement, output "Impossible" (without quotes).


Sample Input

2 BBFSSFSFBBFS
2 BBFSSFSFBB

Sample Output

2
Impossible


Problem Setter: Suhendry Effendy


Pembahasan Problem D - Burger, French Fries, Soft Drink

Anda diberikan urutan paket yang dikeluarkan oleh mesin seperti ini: BBFSSFSFBBFSSBFFSBBSF. Suatu pesanan dianggap valid jika jumlah B sama dengan jumlah F dan S. Misalkan diberi tahu ada N pesanan (N < 30), berapakah "kombinasi" pesanan yang mungkin terjadi kalau mesinnya mengeluarkan output seperti diatas?

Problem ini sengaja disamarkan dengan tidak menggunakan keyword "combination". Kembali ke contoh output mesin diatas, misalkan N = 3 (ada 3 pesanan). Maka kalau dilihat output dari mesin tersebut: BBFSSFSFBBFSSBFFSBBSF, terlihat ada 6 kemungkinan pesanan kecil-kecil yang valid: BBFSSF | SFB | BFS | SBF | FSB | BSF. Berikut adalah 10 possibilities dari pesanan tersebut:

  • (BBFSSF) (SFB) (BFSSBFFSBBSF)
  • (BBFSSF) (SFBBFS) (SBFFSBBSF)
  • (BBFSSF) (SFBBFSSBF) (FSBBSF)
  • (BBFSSF) (SFBBFSSBFFSB) (BSF)
  • (BBFSSFSFB) (BFS) (SBFFSBBSF)
  • (BBFSSFSFB) (BFSSBF) (FSBBSF)
  • (BBFSSFSFB) (BFSSBFFSB) (BSF)
  • (BBFSSFSFBBFS) (SBF) (FSBBSF)
  • (BBFSSFSFBBFS) (SBFFSB) (BSF)
  • (BBFSSFSFBBFSSBF) (FSB) (BSF)

Kalau anda melakukan analisa lebih dalam, akan terlihat rumus nCk berlaku (n choose k). Dalam kasus diatas, jawaban 10 didapat dari nCk(6-1, 3-1) -> (5 choose 2) -> 10 kombinasi pesanan. Kenapa ada -1? anda harus menganalisannya sendiri ;)

Ada cara lain untuk menyelesaikan soal ini tanpa pikir panjang. Yaitu dengan Dynamic Programming versi topdown atau boleh disebut juga rekursi + memoization. Cara ini sangat mudah bagi mereka yang sudah terbiasa melakukan DP Topdown :) Hampir tidak perlu berpikir panjang untuk menyelesaikan soal ini :) Silahkan lihat kode dp-topdown dibawah :)

#include <stdio.h>

int nChooseK(int n, int k){
    long long ret = 1, i;
    for (i=0; i<k; i++)
        ret = ret * (n-i) / (i+1);
    return (int) ret;
}

int main(){
    char s[101];
    int n;

    while (scanf("%d %s",&n,s)!=EOF){
        int G=0,B=0,F=0,S=0,i;

        for (i=0; s[i]; i++){
            if (s[i]=='B') B++;
            else if (s[i]=='F') F++;
            else S++;

            if (B==F && B==S) G++;
        }
        
        if (B!=F || B!=S || G<n)
            puts("Impossible");
        else
            printf("%d\n",nChooseK(G-1,n-1));
    }
}
#include <stdio.h>
#include <string.h>

char s[101];
int len, memo[101][35];

int ok(int L, int R){
    int B=0,F=0,S=0,i;
    for (i=L; i<=R; i++){
        switch (s[i]){
            case 'B' : B++; break;
            case 'F' : F++; break;
            case 'S' : S++; break;
        }
    }
    return B==F && F==S && B>0;
}

int rec(int idx, int n){
    int ret=0, i;

    if (idx>=len) return 0;
    if (n==1) return ok(idx,len-1);
    if (memo[idx][n]!=-1) return memo[idx][n];

    for (i=idx+2; i<len; i++)
        if (ok(idx,i))
            ret += rec(i+1,n-1);

    return memo[idx][n] = ret;
}

int main(){
    int n;

    while (scanf("%d %s",&n,s)!=EOF){
        len = strlen(s);
        memset(memo,-1,sizeof(memo));

        if (rec(0,n)==0)
            puts("Impossible");
        else
            printf("%d\n",rec(0,n));
    }
}

Back to Home

Penyisihan Indonesia National Contest 2007 :: Problem C - No Pause Telegraph

ACM/ICPC Indonesia National Contest 2007 - Qualification

Problem C

No Pause Telegraph

Time Limit: 1s


Several hundreds years ago in a country, there was a war between the colonialist and the military of the country. In the war, telegraph machine was used to communicate between the country and its allied cities around the country. The Morse code was used to send messages through telegraph machine. In Morse, letters are represented only by "." (dot) and "-" (dash). Between letters there is a pause to avoid mistranslation of letters.

In that era with the popularity of telegraph machine, there was wariness that the enemy could read the messages, if the messages were accidentally sent to them. Being aware of the threat, a machine was created to encode the messages. It was called No Pause Telegraph. This new telegraph machine was similar to the regular machine, only that the machine encoded the messages with no pause between letters.

After doing some researches on old relics, our archeologist has analyzed the code being used successfully. The archeologist so far has found 7 letters that been used on the found relics, those are:
A .-- dot dash dash
B -. dash dot
C --- dash dash dash
D .. dot dot
E --.. dash dash dot dot
F --.- dash dash dot dash
G .-. dot dash dot
Your task is to translate several messages encoded by the machine on the remaining relics. You should be careful that any ambiguousity may arise when translating those messages. For example: If the code for X were "." and the code for Y were "..", then two dots in a row could be either XX or Y. For this particular reason, you should output only the least alphabetical solution.


Input Specification

Each line of input is a code encoded by No Pause Telegraph. The line will consists of only characters of . (dot(s)) and - (dash(es)).


Output Specification

For each line of input, print the least alphabetical possible message in one line. If there is no possible message, print "could not be translated" (without quotes).


Sample Input

.---.-
.---.---..--..--.-.-.

Sample Output

could not be translated
ABCDEFG


Problem Setter: Bong Win Ce


Pembahasan Problem C - No Pause Telegraph

Soal ini memberikan anda kode morse. Anda harus men-translasi kode tersebut menjadi huruf-huruf sesuai pengkodean berikut:

A  .--
B  -.
C  ---
D  ..
E  --..
F  --.-
G  .-.
Kode morse "jejadian" diatas adalah unik karena tidak ada prefix dari kode morse yang satu merupakan prefix dari kode morse yang lain. Jadi, suatu rangkaian kode-kode morse yang menggunakan pengkodean diatas pasti dapat ditranslasi menjadi hasil yang unik. Untuk melihat soal lengkapnya, silahkan click link problem statement diatas.

Untuk menyelesaikan soal ini, solusinya straight forward: anda bisa men-translasi satu-persatu kode morse di input menjadi huruf dan menampungnya ke dalam suatu temporary variable. Jika ada input yang tidak ada kode morsenya, maka anda tinggal print "could not be translated" dan berhenti. Jika semua input berhasil ditranslasi, maka print-lah temporary variable-nya. Kodenya dapat dilihat dibawah ini, tersedia 2 versi (C dan Java). Kedua source code ini melakukan hal yang sama dan mempunyai function yang sama. Tetapi solusi Java lebih terlihat manusiawi di function getMorse() karena Java mempunyai built-in method startsWith() di object String yang sangat sesuai untuk problem ini (untuk mengecek apakah suatu kode morse merupakan prefix dari input saat ini).

#include <stdio.h>
#include <string.h>

char input[1000], temp[1000];
char *morse[7] = {".--","-.","---","..","--..","--.-",".-."};

int get_morse(int idx){
    int i,a,b;
    for (i=0; i<7; i++){
        for (a=idx,b=0; ; a++,b++){
            if (morse[i][b]=='\0') return i;
            if (input[a]=='\0' || input[a] != morse[i][b]) break;
        }
    }
    return -1; // kode morse tidak ketemu!
}

char* translate(){
    int i,j,k;
    for (i=j=0; input[i]!='\0'; ){
        k = get_morse(i);
        if (k==-1) return "could not be translated";
        temp[j++] = 'A'+k;
        i += strlen(morse[k]);
    }
    temp[j] = '\0';
    return temp;
}

int main(){
    while (gets(input)){
        puts(translate());
    }
}
import java.util.*;

public class NoPause {
    String[] morse = new String[]{".--","-.","---","..","--..","--.-",".-."};

    public int getMorse(String prefix){
        for (int i=0; i<morse.length; i++)
            if (prefix.startsWith(morse[i])) return i;

        return -1; // kode morse tidak ketemu!
    }

    public String translate(String input){
        String temp = "";
        for (int i=0,j=0; i<input.length(); ){
            int k = getMorse(input.substring(i)); 
            if (k==-1) return "could not be translated";
            temp += (char) ('A'+k);
            i += morse[k].length();
        }
        return temp;
    }

    public void solve(){
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine())
            System.out.println(translate(scan.nextLine()));
        scan.close();
    }

    public static void main(String[] args){
        new NoPause().solve();
    }
}

Back to Home

Penyisihan Indonesia National Contest 2007 :: Problem A - The Chosen Sub Matrix

ACM/ICPC Indonesia National Contest 2007 - Qualification

Problem A

The Chosen Sub Matrix

Time Limit: 1s


From a given N x N matrix, you should find an M x M sub matrix which has the least distinct element in it. If there are more than one sub matrixes which have the same number of distinct elements then compare each element in descending order and choose one that has the first highest element. If all of distinct elements of all sub matrixes are the same, chose one with the least row index, and then the least column index. The matrix index starts at 1.

For example, given a 4x4 matrix:
3 9 9 9
3 9 9 2
3 9 9 2
2 5 5 2

Then, the possible sub matrixes of 3x3 are:
3 9 9
3 9 9
3 9 9
S1
9 9 9
9 9 2
9 9 2
S2
3 9 9
3 9 9
2 5 5
S3
9 9 2
9 9 2
5 5 2
S4
Sub matrix S1 has 2 distinct elements: 9 and 3;
Sub matrix S2 has 2 distinct elements: 9 and 2;
Sub matrix S3 has 4 distinct elements: 9, 5, 3, and 2;
Sub matrix S4 has 3 distinct elements: 9, 5, and 2.
Sub matrixes are ranked using the rules above and give result as S1, S2, S4, and then S3.
Which means the chosen sub matrix is S1.


Input Specification

The first line of each case contains two integers, N (1<=N<=10) the size of matrix, and M (1<=M<=N) the size of sub matrix to be chosen. In the next N lines, each contains N integers (each separated by a space) that represent the matrix. Each element in the matrix should be between 0 and 9 inclusively.


Output Specification

For each case you should output in a single line, the top-left index (row and column, separated by a single space) of the chosen sub matrix.


Sample Input

4 3
3 9 9 9
3 9 9 2
3 9 9 2
2 5 5 2
10 2
1 5 7 8 2 3 3 3 1 7
2 2 3 6 3 7 3 2 3 1
5 9 3 5 7 0 4 6 9 1
1 0 3 4 2 6 4 3 9 0
7 4 9 9 5 4 6 2 1 5
5 6 9 9 6 6 3 8 0 8
4 3 3 5 2 1 7 6 4 1
6 5 9 5 0 3 1 8 8 6
2 2 2 8 0 1 3 5 9 0
3 6 4 2 3 3 0 2 0 0

Sample Output

1 1
5 3


Problem Setter: Bong Win Ce



Pembahasan Problem A - The Chosen Sub Matrix

Anda diberikan matrix N x N berisikan angka dari 0 sampai 9. Anda harus "memilih" sub-matrix M x M yang mempunyai elemen berbeda terkecil. Jika ada sub-matrix yang mempunyai elemen berbeda terkecil yang sama, maka anda harus memilih yang mempunyai elemen terbesar yang tidak sama. Jika masih seri juga, maka pilih yang row nya terkecil, lalu column terkecil.

Algorithm untuk problem ini juga straight forward: cari satu-per-satu diantara semua sub-matrix M x M, update hasil kalau ketemu yang lebih bagus. Anda bisa lihat implementasi algoritma ini dibawah (dalam C maupun Java).

#include <stdio.h>

typedef struct {
    int row, col;    // posisi (row,col) dari Square M x M
    int nums[10];    // num[i] == 1 kalau ada angka i di Square ini,
                     // kalau tidak maka num[i] == 0
                     // dimana i adalah angka antara 0..9
} Square;

// menghitung kemunculan angka i dalam array nums
int count_distinct(int nums[10]){
    int i=0,ret=0;
    for (i=0; i<10; i++)
        if (nums[i]) ret++;
    return ret;
}

// membandingkan dua Square sesuai yang diminta soal
// return true kalau sa lebih bagus dari pada sb
int better(Square *sa, Square *sb){
    int distinct_a = count_distinct(sa->nums);
    int distinct_b = count_distinct(sb->nums);
    int i;

    // pertama tama, bandingkan jumlah angka yang berbeda
    if (distinct_a != distinct_b)
        return distinct_a < distinct_b;

    // kedua, bandingkan kemunculan element tertinggi
    for (i=9; i>=0; i--)
        if (sa->nums[i] != sb->nums[i])
            return sb->nums[i] < sa->nums[i];

    // ketiga, bandingkan baris
    if (sa->row != sb->row) return sa->row < sb->row;

    // perbandingan terakhir adalah kolom
    return sa->col < sb->col;
};


int N,M,arr[10][10];

Square get_square(int r, int c){
    Square square;
    int i,j;

    square.row = r;
    square.col = c;

    for (i=0; i<10; i++)
        square.nums[i] = 0;

    for (i=0; i<M; i++)
        for (j=0; j<M; j++)
            square.nums[arr[r+i][c+j]] = 1;

    return square;
}

int main(){
    int i,j;

    while (scanf("%d %d",&N,&M)!=EOF){
        for (i=0; i<N; i++)
            for (j=0; j<N; j++)
                scanf("%d",&arr[i][j]);

        Square chosen = get_square(0,0);

        for (i=0; i+M<=N; i++)
            for (j=0; j+M<=N; j++){
                Square current = get_square(i,j);
                if (better(&current, &chosen))
                    chosen = current;
            }

        // print square yang terpilih
        printf("%d %d\n",chosen.row+1, chosen.col+1);
    }
}
import java.io.*;
import java.util.*;

public class Matrix {
    int[][] arr = new int[10][10];
    int N, M;

    class Square implements Comparable<Square> {
        int row, col;    // posisi (row,col) dari Square M x M

        int[] nums;      // nums[i] == 1 kalau ada angka i di Square ini,
                         // kalau tidak maka nums[i] == 0
                         // dimana i adalah angka antara 0..9

        // meng-inisialisai data untuk Square pada posisi[r][c]
        public Square(int r, int c){
            row = r;
            col = c;
            nums = new int[10]; // ter-inisialisasi sendiri dengan 0

            // mengisi nums[i] dengan 1 jika ada angka i di Square ini,
            // kalau tidak ada maka nums[i] = 0
            for (int i=0; i<M; i++)
                for (int j=0; j<M; j++)
                    nums[arr[r+i][c+j]] = 1;
        }
    

        // menghitung kemunculan angka i dalam array nums
        int distinctCount(){
            int ret = 0;
            for (int i=0; i<10; i++)
                if (nums[i]==1) ret++;
            return ret;
        }

        // membandingkan dua Square sesuai yang diminta soal
        public int compareTo(Square that){
            int thisDistinct = this.distinctCount();
            int thatDistinct = that.distinctCount();

            // pertama tama, bandingkan jumlah angka yang berbeda
            if (thisDistinct != thatDistinct)
                return thisDistinct - thatDistinct;

            // kedua, bandingkan kemunculan tertinggi
            for (int i=9; i>=0; i--)
                if (this.nums[i] != that.nums[i])
                    return that.nums[i] - this.nums[i];

            // ketiga, bandingkan baris
            if (this.row != that.row) return this.row - that.row;

            // perbandingan terakhir adalah kolom
            return this.col - that.col;
        }
    }

    public void solve(){
        Scanner scan = new Scanner(System.in);

        // baca input selama masih ada integer berikutnya
        while (scan.hasNextInt()){
            N = scan.nextInt(); // baca N
            M = scan.nextInt(); // baca M

            // membaca matrix N x N ke variable arr
            for (int i=0; i<N; i++)
                for (int j=0; j<N; j++)
                    arr[i][j] = scan.nextInt();

            Square chosen = new Square(0,0);

            for (int i=0; i+M<=N; i++)
                for (int j=0; j+M<=N; j++){
                    Square current = new Square(i,j);
                    if (current.compareTo(chosen) < 0)
                        chosen = current;
                }

            // output square yang terpilih
            System.out.printf("%d %d\n",chosen.row+1, chosen.col+1);
        }

        scan.close();
    }

    public static void main(String[] args){
        new Matrix().solve();
    }
}

Back to Home

Penyisihan Indonesia National Contest 2007 :: Problem B - Avoiding Financial Nightmare

ACM/ICPC Indonesia National Contest 2007 - Qualification

Problem B

Avoiding Financial Nightmare

Time Limit: 1s


Nowadays, getting a loan from a bank or financial company has become very popular, either it's for commercial or personal purposes. If you are a well-managed on your expenses, having a loan from a bank or using credit cards for your expenses could be a good help, otherwise it could be your worst financial nightmare. By considering the risks of paying bills, our professor has decided to get a loan to buy a new house on a pleasant city in Indonesia.

Our professor has considered 3 main variables that will affect his monthly bills:
  • Principal, the remaining amount of the loan
  • Period, the number of months to pay off the loan
  • Rate, the monthly interest rate


  • To help their customer, bank or financial company normally offers a fixed amount payment system. Every month the customer should pay a fixed amount of money which consists of two kinds of payment:
    1. Interest Payment.
      Interest Payment = Rate x Remaining Principal.
      The amount of interest payment should be rounded up to the higher nearest integer.

    2. Principal Payment.
      Principal Payment = Total Payment - Interest Payment.
      The previous Principal is to be subtracted with the current Principal Payment to get the current Principal.
    The total monthly payment should be calculated in some way so that the total monthly payment to be paid spread evenly each month, and at the end of the period the remaining Principal is zero or a negative amount nearest to zero (if it's not possible to reach zero).

    For example, let the professor get a loan in the amount of $42,000 with 5% interest rate per month that should be paid in 5 months.
    Term Payment Principal
    Total Interest Payment Principal Payment
    - - - - $42,000
    1 $9,701 $2,100 $7,601 $34,399
    2 $9,701 $1,720 $7,981 $26,418
    3 $9,701 $1,321 $8,380 $18,038
    4 $9,701 $902 $8,799 $9,239
    5 $9,701 $462 $9,239 $0

    1st term: He should pay $9,701 ($2,100 for interest payment, and $7,601 for principal payment)
    Interest Payment : 5% x $42,000 = $2,100
    Principal Payment : $9,701 - $2,100 = $7,601
    Current Principal : $42,000 - $7,601 = $34,399

    2nd term: He pays $9,701 ($1,702 for interest payment, and $7,981 for principal payment)
    Interest Payment : 5% x $34,399 = $1,720
    Principal Payment : $9,701 - $1,720 = $6,902
    Current Principal : $34,399 - $6,902 = $26,418,      and so on.

    Unfortunately, the professor is terrible with financial stuffs. We don't want him to end up broke, do we? So, let us help him with the calculation on how much money he should spend to pay his monthly bills on the loan. In that way, the professor will be able to buy his new house and who knows that someday we might be invited to visit his house in return to our help.


    Input Specification

    The input contains multiple cases. Each case consists of three integers respectively, N (1<=N<=10,000,000) the initial principal, M (1<=M<=100) the period, and R (0<=R<=100) the percent rate.


    Output Specification

    For each case, you should output in a single line the total monthly payment should be made to satisfy the condition.


    Sample Input

    42000 5 5
    100000 10 10
    

    Sample Output

    9701
    16275
    


    Problem Setter: Bong Win Ce


    Pembahasan Problem B - Avoiding Financial Nightmare

    Berapakah biaya bulanan yang harus anda bayar sehingga hutang nya lunas tepat 0 di bulan terakhir atau negative sedikit (jika tidak bisa 0). Cara pembayaran per bulan bisa dilihat rumusnya pada soal, silahkan click problem statement soal diatas. Jika anda sudah mengerti perhitungan di tabel soal, maka yang perlu anda cari adalah berapa total biaya perbulan yang harus dibayar?

    Jebakan untuk soal ini ada 2. Yang pertama adalah Interest Payment harus dibulatkan keatas. Yang kedua, anda akan kena overflow kalau tidak menggunakan tipe data long long di C/C++ atau long di Java. Jika anda mengetahui kedua jebakan ini, anda tetap tidak akan bisa memecahkan soal ini jika tidak tahu algoritma Binary Search. Mungkin saja soal ini bisa diselesaikan hanya dalam 1 rumus, tetapi karena pembulatan saya kira ini akan sangat susah.

    Algoritma binary search analoginya adalah seperti anda mencari suatu kata dalam kamus yang terurut. Dalam kasus problem ini, yang harus anda binary-search adalah "biaya yang harus anda bayar per-bulan". Untuk lebih jelasnya, anda bisa lihat code dibawah. Singkat, padat, jelas :) (saya rasa tidak perlu membuat versi Java atau C++ nya, cuma sedikit sih).

    #include <stdio.h>
    
    int N, M, R;
    
    // pakailah long long untuk menghindari overflow
    long long balance(long long monthly){
        long long P = N, i;
        for (i=0; i<M; i++){
            // ingat, Interest Payment dibulatkan keatas
            long long I = (R * P + 99) / 100;
            P -= monthly - I;
        }
        return P;
    }
    
    int main(){
        while (scanf("%d %d %d",&N,&M,&R)!=EOF){
            int lo = 0, hi = 3*N, res; // jawaban tidak mungkin lebih besar dari 3*N
            // ini algoritma binary search
            while (lo<=hi){
                int med = (lo+hi)/2;
                if (balance(med) <= 0){
                    res = med; // jawaban ditemukan saat nilai balance == 0 atau negative sedikit
                    hi = med-1;
                } else {
                    lo = med+1;
                }
            }
            printf("%d\n",res);
        }
    }
    

    Back to Home