Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <map>
- #include <queue>
- using namespace std;
- class Vertex {
- int x, y;
- public:
- Vertex();
- Vertex(int _x, int _y);
- pair<int, int> operator+ (Vertex& u);
- friend bool operator==(const Vertex& v, const Vertex& u);
- friend bool operator<(const Vertex& v, const Vertex& u);
- friend istream& operator>>(istream& in, Vertex& v);
- friend ostream& operator<<(ostream& in, const Vertex& v);
- };
- Vertex::Vertex() {
- x = 0;
- y = 0;
- }
- Vertex::Vertex(int _x, int _y) {
- x = _x;
- y = _y;
- }
- bool operator==(const Vertex& v, const Vertex& u) {
- return v.x == u.x && v.y == u.y;
- }
- bool operator<(const Vertex& v, const Vertex& u) {
- if (v.x == u.x) {
- return v.y < u.y;
- }
- else {
- return v.x < u.x;
- }
- }
- pair<int, int> Vertex::operator+ (Vertex& u) {
- pair<int, int> result;
- result.first = u.x - this->x;
- result.second = u.y - this->y;
- return result;
- }
- istream& operator>>(istream& in, Vertex& v) {
- in >> v.x >> v.y;
- return in;
- }
- ostream& operator<<(ostream& out, const Vertex& v) {
- out << v.x << " " << v.y;
- return out;
- }
- int height, width;
- const int MAX = 50;
- char field[MAX][MAX];
- map<Vertex, vector<Vertex>> graph;
- map<Vertex, map<Vertex, Vertex>> shortest_way;
- bool check(int x, int y) {
- if ((1 <= x && x <= width) && (1 <= y && y <= height)) {
- return field[x][y] == '1';
- }
- else {
- return false;
- }
- }
- void input() {
- cin >> height >> width;
- for (int i = 1; i <= height; ++i) {
- for (int j = 1; j <= width; ++j) {
- cin >> field[i][j];
- }
- }
- }
- void create_graph() {
- for (int i = 1; i <= height; ++i) {
- for (int j = 1; j <= width; ++j) {
- if (field[i][j] == '1') {
- if (check(i + 1, j)) {
- graph[Vertex(i, j)].push_back(Vertex(i + 1, j));
- }
- if (check(i, j + 1)) {
- graph[Vertex(i, j)].push_back(Vertex(i, j + 1));
- }
- if (check(i, j - 1)) {
- graph[Vertex(i, j)].push_back(Vertex(i, j - 1));
- }
- if (check(i - 1, j)) {
- graph[Vertex(i, j)].push_back(Vertex(i - 1, j));
- }
- }
- }
- }
- }
- void bfs(Vertex st) {
- queue<Vertex> q;
- map<Vertex, bool> used;
- used[st] = true;
- for (auto u : graph[st]) {
- shortest_way[st][u] = u;
- q.push(u);
- used[u] = true;
- }
- while (!q.empty()) {
- Vertex v = q.front();
- q.pop();
- for (auto u : graph[v]) {
- if (!used[u]) {
- q.push(u);
- shortest_way[st][u] = shortest_way[st][v];
- used[u] = true;
- }
- }
- }
- }
- int main() {
- int type;
- cin >> type;
- if (type == 1) {
- input();
- create_graph();
- for (auto vertex : graph) {
- bfs(vertex.first);
- }
- }
- if (type == 2) {
- Vertex v, u;
- cin >> v >> u;
- Vertex next = shortest_way[v][u];
- pair<int, int> result = next + v;
- cout << result.first << " " << result.second;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement