'language/알고리즘'에 해당되는 글 5건

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

당신은 오랜 기간 동안 어머니로부터의 잔소리, TV 혹은 자기 계발 서적 등에서 떠드는 진부한 소리에 세뇌된 끝에 오늘부터 성실히 살기로 결심했다. 그 첫 번째 단계로, 주간 달력을 구매해서 매일 할 일을 달력에 적고 그대로 수행하기로 결정했다. 다음의 예처럼 말이다.

하지만 달력을 사러 나가려는 순간, 당신은 모든 것이 귀찮아졌다. 대신, 집에 굴러다니는 빈 노트에 펜으로 주간 달력을 그려서 대체하기로 결정했다. 그러자 또 다른 문제가 발생했는데 바로 당신이 각 요일이 며칠에 해당하는지 생각하기가 귀찮다는 것이다. 당신은 휴대폰으로 오늘이 몇 월 며칠이며, 무슨 요일인지 알았다. 천만 다행으로 당신을 귀찮게 하지 않는 점은 올해는 윤년이 아니라는 것이다. 이제 컴퓨터 프로그램을 작성하여 주간 달력에 들어갈 숫자들을 완성하라.

첫 줄에는 테스트 케이스의 수 T가 주어진다.

각 테스트 케이스마다 한 줄에 오늘이 몇 월 며칠이며, 무슨 요일인지를 나타내는 2개의 숫자 m,d와 하나의 문자열 s가 하나의 공백을 사이에 두고 입력으로 주어진다. 입력으로 주어지는 m과 d는 달력에 있을 수 있는 날짜이며, 2월 29일인 경우는 없다. 요일을 나타내는 s는 Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday 중 하나이다.

각 테스트 케이스마다 한 줄씩 그 주의 주간 달력에 쓰여야 할 숫자 7개를 하나의 공백을 사이에 두고 일월화수목금토 순으로 출력한다.



#include <iostream>

#include <cstring>

using namespace std;

 

#define START 1

#define END 7

 

char *WEEK[8] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

 

void End_MONTH(int x, int *y, int *z, int a);

void Calculate_INDEX(char* x, int *y);

 

int main() {

 

    int T, END_MON, MON, MON_BEFORE, THIS_DAY, DAYS,INDEX= 0;

    int WEEKDAY[8]={NULL};

    char DAY_CHAR[10]={NULL};

 

    cin>>T;

 

    while(T--){

        cin>>MON>>DAYS>>DAY_CHAR;

 

        End_MONTH(MON, &END_MON, &MON_BEFORE, DAYS);

        Calculate_INDEX(DAY_CHAR, &INDEX);

 

        // 인덱스를 기준으로 배열의 왼쪽을 채움

        THIS_DAY= DAYS;

        for(int i= INDEX; i>= START; i--) {

            WEEKDAY[i-1]= THIS_DAY;

            THIS_DAY--;

            if(THIS_DAY <1) THIS_DAY= MON_BEFORE;

        }

 

        // 인덱스를 기준으로 배열의 오른쪽을 채움

        THIS_DAY= DAYS;

        for(int i= INDEX; i<= END; i++) {

            WEEKDAY[i-1]= THIS_DAY;

            THIS_DAY++;

            if(THIS_DAY >END_MON) THIS_DAY= START;

        }

 

        for(int i= 0; i<6; i++) {

            cout<<WEEKDAY[i]<<" ";

        }

        cout<<WEEKDAY[6]<<endl;

    }

 

    system("pause");

}

 

// 현재 , 지난 월의 마지막 일수를 계산해서 저장

// 다음 달의 경우, 1일부터 시작하므로 변수에 저장하지 않음

void End_MONTH(int x, int *y, int *z, int a) {

 

    // 일수가 31일인

    if(x == 1 || x == 3 || x == 5 || x == 7 || x == 8 || x == 10 || x == 12) {

 

        // 예외값 처리

        if(a <1 || a> 31) exit(1);

 

        //8월과 1월의 경우, 지난 달의 일수는 31

        if(x == 8 || x == 1) {

            *y= 31; *z= 31;

            return;

        }

 

        // 3월의 경우, 지난 달의 일수는 28

        if(x == 3) {

            *y= 31; *z= 28;

        }

 

        *y= 31; *z= 30;

        return;

    }

 

    // 일수가 28일인 2

    else if(x == 2) {

        if(a <1 || a> 28) exit(1);

        *y= 28; *z= 31;

        return;

    }

 

    // 일수가 30일인

    else {

        if(a <1 || a> 30) exit(1);

        *y= 30; *z= 31;

        return;

    }

}

 

// 입력받은 문자열이 주의 번째 일수에 위치하는지 인덱스 계산

void Calculate_INDEX(char* x, int *y) {

 

    int k= 0;

 

    for(int i=0; i<END; i++) {

        k =strcmp(x, WEEK[i]);

        if(k== 0) {

            *y= i+1;

            return;

        }

    }

    if(*y ==0)

        exit(1);

}



출력 결과만 보면 문제가 없는 것처럼 보이나, 답안 제출 시 오답 판정된다.


디버깅이 끝나면 해당 부분을 고쳐 수정할 계획이다.





'language > 알고리즘' 카테고리의 다른 글

MISPELL  (0) 2016.07.19
XOR 연산자를 이용한 Swap  (0) 2016.07.18
ENDIANS  (0) 2016.07.18
알고리즘: 효율, 분석 그리고 차수  (0) 2016.07.10
블로그 이미지

saylin

,

MISPELL

language/알고리즘 2016. 7. 19. 00:16
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

MISPELL 

Misspelling is an art form that students seem to excel at. Write a program that removes the nth
character from an input string.

The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

Each dataset consists of a single line of input containing M, a space, and a single word made up of uppercase letters only. M will be less than or equal to the length of the word. The length of the word is guaranteed to be less than or equal to 80.

For each dataset, you should generate one line of output with the following values: The dataset

number as a decimal integer (start counting at one), a space, and the misspelled word. The
misspelled word is the input word with the indicated character deleted.

(출처: 알고스팟, https://algospot.com/judge/problem/read/MISPELL)


문제 푸는 방식은 다양하다.

나는 입력받은 숫자 M에 해당하는 문자열 순서 이후의 문자열들을 한칸 앞으로 끌어와 덮어씌우고

최종적으로 완성된 문자열들을 출력하는 방식을 사용했다.

다른 사람의 경우, 아예 해당 문자열 부분은 출력하지 않고 이어서 출력하도록 구현한 것을 볼 수 있었다.


#include <iostream>

#include <cstring>

 

using namespace std;

 

int main()

{

                  int T, i=1;

                 

                  int count, length;

                  char str[81]={NULL};

 

                  cin>>T;

                 

                  while(T--){

                                   cin>>count>>str;

                                   length=strlen(str);

                 

                                   cout << i << " ";

 

                                   for(int j=count-1; j<=length-1; j++){

                                                     str[j]=str[j+1];

                                   }

                                   for(int j=0; j<=length-1; j++){

                                                     cout<<str[j];

                                   }

                                   cout<<endl;

                                   i++;

                  }

                  system("pause");

                  return 0;

}


#include <iostream>

#include <cstring>

 

using namespace std;

 

int main()

{

                  int T, i=1;

                 

                  int count, length;

                  char str[81]={NULL};

 

                  cin>>T;

                 

                  while(T--){

                                   cin>>count>>str;

                                   length=strlen(str);

                 

                                   cout << i << " ";

 

                                   for(int j=count-1; j<=length-1; j++){

                                                     str[j]=str[j+1];

                                   }

                                   for(int j=0; j<=length-2; j++){

                                                     cout<<str[j];

                                   }

                                   cout<<endl;

                                   i++;

                  }

                  system("pause");

                  return 0;

}


위 두 코드들은 거의 같지만 단 한 글자만 다르다. 위는 오답, 아래는 정답으로 인정되었다.


length-1의 경우, 보이지 않는 NULL 문자열 또한 같이 출력되기 때문에 

화면 상으로는 보이지 않더라도 정답으로 인정하지 않는 것 같다.





'language > 알고리즘' 카테고리의 다른 글

WEEKLYCALENDAR  (0) 2016.07.31
XOR 연산자를 이용한 Swap  (0) 2016.07.18
ENDIANS  (0) 2016.07.18
알고리즘: 효율, 분석 그리고 차수  (0) 2016.07.10
블로그 이미지

saylin

,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

1. 교환법칙 : A^B=B^A

2. 결합법칙: (A^B)^C = A^(B^C)

3. 항등원 존재 : A^0 = 0^A = A

4. 역원 존재 A^A1=0


위의 4가지는 모든경우의 수를 대입하면 증명할 수 있습니다.


1.교환법칙 증명

모든 경우의수 AB

00 >>>>> 같으므로 생략

01 >>>>>  0^1 = 1,  1^0 = 1  좌측, 우측 같음 

10 >>>>>  1^0 = 1,  0^1 = 1  좌측, 우측 같음

11 >>>>> 같으므로 생략

모든 경우 같으므로 증명됨


2.결합법칙 증명

모든 경우의 수 ABC

000 >>>>> 같으므로 생략

001 >>>>> (0^0)^1 = 1, 0^(0^1)= 1 좌측, 우측 같음

010 >>>>> (0^1)^0 = 1, 0^(1^0)= 1 좌측, 우측 같음

011 >>>>> (0^1)^1 = 0, 0^(1^1)= 0 좌측, 우측 같음

100 >>>>> (1^0)^0 = 1, 1^(0^0)= 1 좌측, 우측 같음

101 >>>>> (1^0)^1 = 0, 1^(0^1)= 0 좌측, 우측 같음

110 >>>>> (1^1)^0 = 0, 1^(1^0)= 0 좌측, 우측 같음

111 >>>>> 같으므로 생략

모든경우 같으므로 증명됨


3. 항등원 존재

모든 경우의 수  A

0 >>>>>  0^0 = 0^0 = 0,  같음

1 >>>>>  1^0 = 0^1 = 1, 같음

모든 경우 같으므로 항등원 0 존재 증명됨



4. 역원

모든 경우의 수  A

0 >>>>>  0^0 = 0, 

1 >>>>>  1^0 = 1 ,

항등원 0의 역원 A1  는 A 자신임






위의 사실을 바탕으로 XOR SWAP 알고리즘을 살펴보면

==============================================


순서대로 0, 1, 2, 3 살펴보면



0. 처음 상태 ----------------A----------------B----------------


1.     A=A^B---------------- A^B ------------- B----------------


2.     B=B^A ----------------A^B -----------B^(A^B)-------------



B^(A^B)      는

B^(B^A)  교환법칙 적용

(B^B)^A  결합 법칙 적용, 역원이 자기 자신이니 (B^B)= 0

0^A 항등원이 존재하므로

A 가 됩니다.



3. A=A^B ----------------(A^B)^A----------------A---------------


(A^B)^A  는

(B^A)^A 교환법칙

B^(A^A) 결합법칙 , 역원이 자기 자신이니 (A^A=0)

B^0 항등원이 존재하므로 이므로

B 가 됩니다.



     결과 ----------------B---------------- A----------------



스왑이 일어나는것을 확인 할 수 있습니다.



(출처: http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=230636611&qb=YysrIHhvcg==&enc=utf8&section=kin&rank=1&search_sort=0&spq=0&pid=SGwBNsoRR1dssvp6tX4sssssssG-168491&sid=kKuYgjVn5WDRDdonE69m3g%3D%3D)



'language > 알고리즘' 카테고리의 다른 글

WEEKLYCALENDAR  (0) 2016.07.31
MISPELL  (0) 2016.07.19
ENDIANS  (0) 2016.07.18
알고리즘: 효율, 분석 그리고 차수  (0) 2016.07.10
블로그 이미지

saylin

,

ENDIANS

language/알고리즘 2016. 7. 18. 06:21
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

ENDIANS

The two island nations Lilliput and Blefuscu are severe rivals. They dislike each other a lot, and the most important reason was that they break open boiled eggs in different ways.

People from Lilliput are called little-endians, since they open eggs at the small end. People from Blefuscuare called big-endians, since they open eggs at the big end.

This argument was not only about their breakfasts but about their computers, too. Lilliput and Blefuscu's computers differed in the way they store integers; they stored the bytes in different orders. Computers from Lilliput(*little-endians*) ordered it from the LSB(least significant byte) to the MSB(most significant byte), and computers from Blefuscu was exactly the opposite.

For example, a 32-bit unsigned integer 305,419,896 (0x12345678) would be saved in two different ways:

For example, a 32-bit unsigned integer 305,419,896 (0x12345678) would be saved in two different ways:

  • 00010010 00110100 01010110 01111000 (in an Blefuscu computer)
  • 01111000 01010110 00110100 00010010 (in an Lilliput computer)

Given some 32-bit unsigned integers retrieved in a wrong endian, write a program to do a conversion to find the correct value.


The first line of the input file will contain the number of test cases, C (1 ≤ C ≤ 10, 000). Each test case contains a single 32-bit unsigned integer, which is the data without endian conversion.

For each test case, print out the converted number.

(출처: 알고스팟, https://algospot.com/judge/problem/read/ENDIANS)


비트 연산은 자주 사용해보지 않아서 이해하고 구현하는데 약간의 시간이 걸렸다.

위와 같은 연산을 구현하기 위해서 다음과 같이 실험적인 코드 작성 및 컴파일을 수행했다.



#include <iostream>

#include <bitset>

using namespace std;

 

int main(){

                  //int cases;

                  unsigned int x=2018915346;

                  //cin >> cases;

 

                  unsigned int a, b, c, d, e;

 

                  a = (x>>24);

                  b = (x<<8)>>24<<8;

                  c = (x>>8)<<24>>8;

                  d = (x<<24);

                 

                  cout<< bitset<32>(x) <<endl;

                  cout<< bitset<32>(a) <<endl;

                  cout<< a <<endl;

                  cout << bitset<32>(b) << endl;

                  cout<< b <<endl;

                  cout << bitset<32>(c) << endl;

                  cout<< c <<endl;

                  cout << bitset<32>(d) << endl;

                  cout<< d <<endl;

                                   //while(cases--){

                                                     e=a+b+c+d;

                                                     cout <<e <<endl;

                                   //}

                  getchar();

}




출력된 결과 화면



위 결과를 토대로 다음과 같이 간단한 코드로 변환했다.


#include <iostream>

using namespace std;

 

int main(){

                  int cases;

                  unsigned int x;

                  cin >> cases;


                  while(cases--){

                                   cin >> x;

                                   cout <<(x>>24)+((x<<8)>>24<<8)+((x>>8)<<24>>8)+(x<<24) <<endl;

                  }

}



간단한 코드임에도 실행 시간이 58ms 이었다. 

이보다 더 긴 코드임에도 불구하고 실행시간이 5ms인 경우도 있는걸 보니, 위 코드가 매우 효율적이지는 않은 것 같다.





'language > 알고리즘' 카테고리의 다른 글

WEEKLYCALENDAR  (0) 2016.07.31
MISPELL  (0) 2016.07.19
XOR 연산자를 이용한 Swap  (0) 2016.07.18
알고리즘: 효율, 분석 그리고 차수  (0) 2016.07.10
블로그 이미지

saylin

,