문제: https://www.acmicpc.net/problem/1022
규칙성을 찾아 좌표에 따른 각 숫자를 얻는 함수를 만들어 문제를 풀었습니다.
my solving
c++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | #include <fstream> #include <iostream> #include <cstring> #include <climits> #include <algorithm> #include <vector> using namespace std; int getDigit(int n) { int ret = 0; while (n > 0) { ret++; n /= 10; } return ret; } int getSpiralNumber(int y, int x) { int maxCoordinate = max(abs(y), abs(x)); int maxNum = (2 * maxCoordinate + 1) * (2 * maxCoordinate + 1); int minNum = maxNum - maxCoordinate * 8 + 1; if (x == maxCoordinate && y != maxCoordinate) return minNum + maxCoordinate - y - 1; else if (y == maxCoordinate * -1) return minNum + (maxCoordinate * 2) + maxCoordinate - x - 1; else if (x == maxCoordinate * -1) return minNum + (maxCoordinate * 4) + maxCoordinate + y - 1; else return minNum + (maxCoordinate * 6) + maxCoordinate + x - 1; } int main() { int r1, c1, r2, c2; cin >> r1 >> c1 >> r2 >> c2; vector<int> ret; int maxDigit = 0; for (int y = r1; y <= r2; y++) { for (int x = c1; x <= c2; x++) { int num = getSpiralNumber(y, x); maxDigit = max(maxDigit, getDigit(num)); ret.push_back(num); } } int curX = c1; for (vector<int>::iterator it = ret.begin(); it != ret.end(); it++) { if (curX == c2 + 1) { cout << endl; curX = c1; } else if (curX != c1) cout << " "; int digit = getDigit(*it); while (digit != maxDigit) { cout << " "; digit++; } cout << *it; curX++; } return 0; } | cs |
'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글
BAEKJOON 1026 - 보물 (0) | 2016.08.09 |
---|---|
BAEKJOON 1024 - 수열의 합 (0) | 2016.08.08 |
BAEKJOON 1021 - 회전하는 큐 (0) | 2016.08.03 |
BAEKJOON 1019 - 책 페이지 (0) | 2016.08.02 |
BAEKJOON 1018 - 체스판 다시 칠하기 (0) | 2016.08.02 |