|
1 | | -// Authored by : jimi567 |
| 1 | +// Authored by : keyboardmunji |
2 | 2 | // Co-authored by : - |
3 | | -// http://boj.kr/7d30341579424e59a3868fc91e1980d6 |
| 3 | +// http://boj.kr/904f8aa97bd644f9a0633199b5cf6285 |
4 | 4 | #include <bits/stdc++.h> |
5 | 5 | using namespace std; |
| 6 | + |
6 | 7 | #define X first |
7 | 8 | #define Y second |
8 | | -#define ll long long |
9 | | -int n, m; |
10 | | -int arr[1005][1005]; |
11 | | -int ans = 0x7f7f7f7f; |
12 | | -vector<int> idx; //각 팀들의 현재 인덱스를 저장하는 벡터. |
| 9 | + |
| 10 | +int n, m, cnt, en, ans = 0x7f7f7f7f; |
| 11 | +int chk[1005]; // 각 팀이 구간속에 모두 있는지 확인하는 벡터 |
| 12 | +vector<pair<int, int>> a; // 능력치와 각팀의 인덱스를 저장하는 벡터 |
| 13 | + |
13 | 14 | int main(void) { |
14 | 15 | ios::sync_with_stdio(0); |
15 | 16 | cin.tie(0); |
| 17 | + |
16 | 18 | cin >> n >> m; |
17 | 19 | for (int i = 0; i < n; i++) { |
18 | | - idx.push_back(0); |
19 | | - for (int j = 0; j < m; j++) cin >> arr[i][j]; |
| 20 | + for (int j = 0; j < m; j++) { |
| 21 | + int num; |
| 22 | + cin >> num; |
| 23 | + a.push_back({num, i}); |
| 24 | + } |
20 | 25 | } |
21 | | - for (int i = 0; i < n; i++) sort(arr[i], arr[i] + m); |
22 | | - while (1) { |
23 | | - int mntm; |
24 | | - int mx = -1; |
25 | | - int mn = 0x7f7f7f7f; |
26 | | - for (int i = 0; i < n; i++) { |
27 | | - if (mn > arr[i][idx[i]]) { //최솟값 갱신, 최솟값을 가지는 팀 갱신 |
28 | | - mn = arr[i][idx[i]]; |
29 | | - mntm = i; |
30 | | - } |
31 | | - if (mx < arr[i][idx[i]]) mx = arr[i][idx[i]]; //최댓값 갱신 |
| 26 | + sort(a.begin(), a.end()); |
| 27 | + |
| 28 | + for (int st = 0; st < n * m; st++) { |
| 29 | + // 구간 속에 각 팀이 모두 포함되게 en을 증가 |
| 30 | + while (cnt < n && en < n * m) { |
| 31 | + if (chk[a[en].Y] == 0) cnt++; |
| 32 | + chk[a[en].Y]++; |
| 33 | + en++; |
32 | 34 | } |
33 | | - ans = min(ans, mx - mn); |
34 | | - idx[mntm] += 1; |
35 | | - if (idx[mntm] == m) |
36 | | - break; //만약 최솟값을 가지는 팀이 마지막 인덱스에 해당하면 종료. |
| 35 | + if (cnt != n) break; |
| 36 | + ans = min(ans, a[en - 1].X - a[st].X); |
| 37 | + chk[a[st].Y]--; |
| 38 | + if (chk[a[st].Y] == 0) cnt--; |
37 | 39 | } |
38 | 40 | cout << ans; |
| 41 | + return 0; |
39 | 42 | } |
0 commit comments