배열(Array)

백준 2669번 : 직사각형 네개의 합집합의 면적 구하기

cepiloth 2018. 6. 17. 10:02
반응형


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


1. 문제 요약

평면에 네 개의 직사각형이 놓여 있는데 그 밑변은 모두 가로축에 평행하다. 이 네 개의 직사각형들은 서로 떨어져 있을 수도 있고, 겹쳐 있을 수도 있고, 하나가 다른 하나를 포함할 수도 있으며, 변이나 꼭지점이 겹칠 수도 있다. 이 직사각형들이 차지하는 면적을 구하는 프로그램을 작성하시오.


2. 알고리즘


입력의 제한은 1 부터 100 까지 이다. 

2차원 배열 board[101][101] 을 선언 하고 0 으로 초기화 한다.


다음으로 입력으로 들어오는 값은 사각형의 좌표 x, y, w, h 입력 된다. 

1
2
3
4
5
6
7
int x,y,w,h; cin >> x >> y >> w >> h;
 
for(int i=x; i<w; i++) {
    for(int j=y; j<h; j++) {
        board[i][j] = 1;
    }
}
cs


2차원 반복문을 통해 주어진 위치를 1로 초기화 한다.


3. 코드

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
#include <iostream>
#include <sstream>
#include <string>
 
using namespace std;
 
int main() {
    
    std::ios::sync_with_stdio(false); cin.tie(0);
 
    int board[101][101= {0,};
 
    int n = 4;
    while(n--) {
        int x,y,w,h; cin >> x >> y >> w >> h;
 
        for(int i=x; i<w; i++) {
            for(int j=y; j<h; j++) {
                board[i][j] = 1;
            }
        }
    }
 
    int sol = 0;
    for(int i=0; i<101; i++) {
        for(int j=0; j<101; j++) {
            if(board[i][j]) {
                sol ++;
            }
        }
    }
 
    cout << sol << "\n";
    return 0;
}
cs


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
#include <iostream>
#include <sstream>
#include <string>
 
using namespace std;
 
/*
* @brief : 입력과 동시에 count 
*/
int main() {
    
    std::ios::sync_with_stdio(false); cin.tie(0);
 
    int board[101][101= {0,};
 
    int n = 4;
    
  int sol = 0;
    while(n--) {
        int x,y,w,h; cin >> x >> y >> w >> h;
 
        for(int i=x; i<w; i++) {
            for(int j=y; j<h; j++) {
         if(board[i][j]) {
          continue;
          }
                  board[i][j] = 1;
          sol++;
            }
        }
    }
 
    cout << sol << "\n";
    return 0;
}
cs

반응형