-
Educational Codeforces Round 36 (Rated for Div. 2) - B. Browser코드포스(CodeForce) 2018. 8. 17. 18:23반응형
1. 문제
2. 알고리즘
키워드 - 구현
* 최노키오 소견
재훈씨
문제를 한번에 풀라고 생각하지 말고
불변식을 만들어서 하세요.
문제에 제약사항(불변식)을 두어서 풀기 간단하게 만들자.
ex) if문 분기로 한번에 최적해를 구하려고 하면 if문들에 의해 많은 난해함이 생긴다. -> if문을 줄일 방법은 무엇인가?
3. 코드
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#include<iostream>#include<algorithm>#include<string.h>#include<memory.h>#include<vector>using namespace std;int main(){int n, pos, left, right;cin >> n >> pos >> left >> right;bool needDelLeft = (left == 1) ? false : true;bool needDelRight = (right == n) ? false : true;int cand1 = 0, cand2 = 0;int tmpPos = pos;// 왼쪽처리 후 오른쪽 처리if (needDelLeft) {cand1 += abs(tmpPos - left);cand1++;tmpPos = left;}if (needDelRight) {cand1 += abs(tmpPos - right);cand1++;tmpPos = right;}// 오른쪽처리 후 왼쪽 처리tmpPos = pos;if (needDelRight) {cand2 += abs(right - tmpPos);cand2++;tmpPos = right;}if (needDelLeft) {cand2 += abs(tmpPos - left);cand2++;tmpPos = left;}int sol = min(cand1, cand2);cout << sol;return 0;}cs 반응형'코드포스(CodeForce)' 카테고리의 다른 글