PS/기타 알고리즘

[3009] 네 번째 점

프레딕 2023. 2. 5. 16:05
728x90

https://www.acmicpc.net/problem/3009

문제

세 점이 주어졌을 때, 축에 평행한 직사각형을 만들기 위해서 필요한 네 번째 점을 찾는 프로그램을 작성하시오.

입력

세 점의 좌표가 한 줄에 하나씩 주어진다. 좌표는 1보다 크거나 같고, 1000보다 작거나 같은 정수이다.

출력

직사각형의 네 번째 점의 좌표를 출력한다.

코드1

#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <set>
#include <vector>
using namespace std;

int x, y;
map<int, int> mx;
map<int, int> my;
int ret1, ret2;

int main(void) {
  for (int i = 0; i < 3; ++i) {
    cin >> x >> y;

    if (mx[x] == 1) {
      mx[x] = 2;
    } else {
      mx[x] = 1;
    }
		if (my[y] == 1) {
      my[y] = 2;
    } else {
      my[y] = 1;
    }
  }

 	for(auto iter = mx.begin(); iter != mx.end(); ++iter){
		if(iter->second == 1){
			ret1 = iter->first;
			break;
		}
	}
		for(auto iter = my.begin(); iter != my.end(); ++iter){
		if(iter->second == 1){
			ret2 = iter->first;
			break;
		}
	}

  cout << ret1 << ' ' << ret2;

  return 0;
}

내가 처음짠 코드이다. map에 익숙치 않은 상태라 코드가 많이 더럽다. map에 대해 몇가지 조사해보니 아래 코드와 같이 수정할 수 있었다.

 

코드2

#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <set>
#include <vector>
using namespace std;

int x, y;
map<int, int> mx;
map<int, int> my;
int ret1, ret2;

int main(void) {
  for (int i = 0; i < 3; ++i) {
    cin >> x >> y;

    mx[x]++;
    my[y]++;
  }

  for(auto iter : mx){
    if(iter.second==1){
      ret1 = iter.first;
      break;
    }
  }
  
   for(auto iter : my){
    if(iter.second==1){
      ret2 = iter.first;
      break;
    }
  }

  cout << ret1 << ' ' << ret2;

  return 0;
}

map<int, int> 의 초기값은 second번째 자리가 0으로 설정되어있다.

예를 들어 mx[10] 의 초기값은 0 으로 되어있어서 바로 ++연산이 가능하다.

또한 map을 순회하는 방법을 위와 같은 코드로 간략화 할 수 있다.

728x90
반응형