Programozás‎ > ‎Feladatok‎ > ‎Varázslat‎ > ‎Megoldás‎ > ‎

ep_varazslat.java

Letöltés: ep_varazslat.java

package ep_varazslat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

class M {
    int C,D,N;
    String[] comb;
    String[] opp;
    String invoke;
    char[] sol;
    int slen;

    public M(String line){
        String[] data = line.split(" ");
        C = Integer.parseInt(data[0]);
        comb = new String[C];
        for(int i=0; i<C; i++){
            comb[i] = data[i+1];
        }
        D = Integer.parseInt(data[C+1]);
        opp = new String[D];
        for(int i=0; i<D; i++){
            opp[i] = data[i+C+2];
        }
        N = Integer.parseInt(data[D+C+2]);
        invoke = data[D+C+3];

        sol = new char[N];
    }

    public char combine(char last, char c){
        char ret = ' ';
        for(int i = 0; i<C; i++){
            if(     (comb[i].charAt(0)==last && comb[i].charAt(1)==c)||
                    (comb[i].charAt(1)==last && comb[i].charAt(0)==c)){
                ret = comb[i].charAt(2);
                break;
            }
        }

        return ret;
    }

    public boolean delete(char[] s, int slen, char c){
        for(int i = 0; i<slen; i++){
            for(int j = 0; j < D; j++){
                if(     (opp[j].charAt(0)==s[i] && opp[j].charAt(1)==c)||
                        (opp[j].charAt(1)==s[i] && opp[j].charAt(0)==c)){
                    return true;
                }
            }
        }
        return false;
    }

    public String solution(){
        slen = 1;
        sol[0] = invoke.charAt(0);
        char last = sol[0];

        for(int i = 1; i < N; i++){
            char c = invoke.charAt(i);

            char cc = combine(last,c);      //új elem
            if(cc != ' ') {
                sol[slen-1] = cc;
                last = cc;
            } else if(delete(sol,slen,c)){  // teljes törlés
                slen = 0;
                last = ' ';               
            } else {                        // hozzáfűzés
                sol[slen++] = c;
                last = c;
            }
        }

        // válasz összeragasztása
        String ret = "[";
        for(int i = 0; i < slen-1; i++){
            ret += sol[i]+", ";
        }
        if(slen > 0) ret += sol[slen-1];
        ret +="]";

        return ret;
    }
}

public class ep_varazslat {
    public static void main(String[] args) throws FileNotFoundException,IOException {
    
        BufferedReader in = new BufferedReader(new FileReader("BS.in"));
        String line = in.readLine();
        int T = Integer.parseInt(line);
        for(int i = 1; i <= T; i++){
            line = in.readLine();
            M solver = new M(line);
            System.out.format("Case #%d: %s\n", i, solver.solution());
        }
    }
}