Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <queue>
- using namespace std;
- const int MAX_N = 1000;
- //vector<vector<int>> graph(MAX_N, vector<int>());
- int trees[MAX_N][MAX_N];
- int visited[MAX_N][MAX_N];
- int arr[MAX_N*MAX_N];
- int n,d;
- void clearVisited()
- {
- for(int i = 0; i < n; ++i)
- {
- for(int j = 0; j < n; ++j)
- {
- visited[i][j] = 0;
- }
- }
- }
- bool canBuild(int oldest)
- {
- queue<pair<int,int>> Q;
- queue<int> Q2;
- for(int i = 0; i < n; ++i)
- {
- for(int j = 0; j < n; ++j)
- {
- if(!visited[i][j])
- {
- visited[i][j] = 1;
- Q.push(pair<int,int>(i,j));
- Q2.push(1);
- while(!Q.empty())
- {
- pair<int,int> coords = Q.front();
- Q.pop();
- int volume = Q2.front();
- Q2.pop();
- if(volume >= d)
- {
- clearVisited();
- return 1;
- }
- if(coords.first > 0)
- {
- if(trees[coords.first-1][coords.second] <= oldest && !visited[coords.first-1][coords.second])
- {
- visited[coords.first-1][coords.second] = 1;
- Q.push(pair<int,int>(coords.first-1, coords.second));
- Q2.push(volume+1);
- }
- }
- if(coords.first < n-1)
- {
- if(trees[coords.first+1][coords.second] <= oldest && !visited[coords.first+1][coords.second])
- {
- visited[coords.first+1][coords.second] = 1;
- Q.push(pair<int,int>(coords.first+1, coords.second));
- Q2.push(volume+1);
- }
- }
- if(coords.second > 0)
- {
- if(trees[coords.first][coords.second-1] <= oldest && !visited[coords.first][coords.second-1])
- {
- visited[coords.first][coords.second-1] = 1;
- Q.push(pair<int,int>(coords.first, coords.second-1));
- Q2.push(volume+1);
- }
- }
- if(coords.second < n-1)
- {
- if(trees[coords.first][coords.second+1] <= oldest && !visited[coords.first][coords.second-1])
- {
- visited[coords.first][coords.second+1] = 1;
- Q.push(pair<int,int>(coords.first, coords.second+1));
- Q2.push(volume+1);
- }
- }
- }
- }
- }
- }
- clearVisited();
- return 0;
- }
- int main() {
- int w;
- cin >> n >> d;
- for(int i = 0; i < n; ++i)
- {
- for(int j = 0; j < n; ++j)
- {
- cin >> w;
- trees[i][j] = w;
- arr[i*n+j] = w;
- }
- }
- sort(arr, arr + n*n);
- int l = 0, r = n*n-1, mid;
- int res;
- while(l <= r)
- {
- mid = (l+r)/2;
- if(canBuild(mid))
- {
- r = mid - 1;
- res = mid;
- }
- else
- {
- l = mid + 1;
- }
- }
- cout << mid;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement