Created
July 3, 2017 07:48
-
-
Save KirillLykov/d2dcd997f538a7af540c19056a8431ae to your computer and use it in GitHub Desktop.
Solution for the grid of many xor using prim algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <bits/stdc++.h> | |
| using namespace std; | |
| struct Node { | |
| int w; | |
| pair<int, int> c; | |
| Node(int wi, int xi, int yi) | |
| : w(wi), c(xi, yi) | |
| {} | |
| bool operator< (const Node& another) const { | |
| return w < another.w; | |
| } | |
| }; | |
| long long prim(vector< vector<int> >& mat) { | |
| set< Node > q; | |
| q.insert( Node(0, 0, 0) ); | |
| vector< vector<int> > keys(mat.size(), vector<int>(mat[0].size(), numeric_limits<int>::max())); | |
| vector< vector<bool> > visited(mat.size(), vector<bool>(mat[0].size(), false)); | |
| keys[0][0] = 0; | |
| while (!q.empty()) { | |
| auto u = *q.begin(); | |
| visited[u.c.first][u.c.second] = true; | |
| q.erase(q.begin()); | |
| for (int i = 0; i < 2; ++i) | |
| for (int j = 0; j < 2; ++j) { | |
| int s = 1 - 2*i; | |
| int x = s * j; | |
| int y = s * (!j); | |
| if (u.c.first+x >= 0 && u.c.second+y >=0 && | |
| u.c.first+x < mat.size() && u.c.second+y < mat[0].size()) { | |
| int cost = mat[u.c.first+x][u.c.second+y] ^ mat[u.c.first][u.c.second]; | |
| if (!visited[u.c.first+x][u.c.second+y] && | |
| keys[u.c.first+x][u.c.second+y] > cost) { | |
| q.erase( Node(keys[u.c.first+x][u.c.second+y], u.c.first+x, u.c.second+y) ); | |
| keys[u.c.first+x][u.c.second+y] = cost; | |
| q.insert( Node(keys[u.c.first+x][u.c.second+y], u.c.first+x, u.c.second+y) ); | |
| } | |
| } | |
| } | |
| } | |
| long long res = 0; | |
| for (int i = 0; i < mat.size(); ++i) { | |
| for (int j = 0; j < mat[0].size(); ++j) { | |
| res += keys[i][j]; | |
| } | |
| } | |
| return res; | |
| } | |
| int main() | |
| { | |
| int T; | |
| cin >> T; | |
| for (int t = 0; t < T; ++t) { | |
| int n, m; | |
| cin >> n >> m; | |
| int r1,c1,r2,c2; | |
| cin >> r1 >> c1 >> r2 >> c2; | |
| vector< vector<int> > mat(n, vector<int>(m, 0)); | |
| for (int i = 0; i < n; ++i) | |
| for (int j = 0; j < m; ++j) | |
| cin >> mat[i][j]; | |
| cout << prim(mat) << "\n";; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment