Islands UVA

来源:互联网 发布:淘宝我的评价在哪里找 编辑:程序博客网 时间:2024/05/21 22:47

本题考查并查集的使用读入对应的点的信息,包括点的坐标以及该点的高度,同时要计算出将二维坐标转换为一维坐标的值,然后读入T个数。将点按照高度逆序排序,然后从第T个数开始倒序作为阈值处理相应的点,计算出对应的区域个数,存储,最终输出即可,注意并查集在统计连通块个数时候的使用,具体实现见如下代码:

#include<iostream>#include<vector>#include<string>#include<set>#include<stack>#include<queue>#include<map>#include<algorithm>#include<cmath>#include<iomanip>#include<cstring>#include<sstream>#include<cstdio>#include<deque>#include<functional>using namespace std;typedef long long ll;class point{public:int x, y;int id, height;};bool compare(const point& a, const point& b){return a.height > b.height;}int parent[1000010];int dx[] = { 0, 0, 1, -1 };int dy[] = { 1, -1, 0, 0 };class Solve{public:int n, m;int T;vector<point> p;vector<int> H;int total;void Init(){p.clear();H.clear();cin >> n >> m;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){point temp;temp.x = i;temp.y = j;temp.id = i*m + j;cin >> temp.height;p.push_back(temp);parent[temp.id] = -1;}}sort(p.begin(), p.end(), compare);cin >> T;for (int i = 0; i < T; i++){int t;cin >> t;H.push_back(t);}}int find_root(int i){if (i == -1) return -1;if (parent[i] == i) return i;return parent[i]=find_root(parent[i]);}void add(int ind){int id = p[ind].id;parent[id] = id;total++;for (int i = 0; i < 4; i++){int x = p[ind].x + dx[i];int y = p[ind].y + dy[i];if (x >= 0 && x < n&&y >= 0 && y < m){int id2 = x*m + y;int root_id2 = find_root(id2);if (root_id2 == -1) continue;if (root_id2 != id){total--;parent[root_id2] = id;}}}}void Deal(){Init();int ind = 0;total = 0;for (int i = H.size() - 1; i >= 0; i--){while (ind < p.size() && H[i] < p[ind].height) add(ind++);H[i] = total;}for (int i = 0; i < H.size(); i++){cout << H[i] << " ";}cout << endl;}};int main(){int Case;cin >> Case;Solve a;while (Case--){a.Deal();}return 0;}

原创粉丝点击