Re: [闲聊] 每日leetcode

楼主: oin1104 (是oin的说)   2024-10-07 14:02:16
每日太水
来写个不一样的
题目;
1584. Min cost to connect all point
用最短的路把所有点都连在一起
路径长直接用x跟y的差距就好
叫啥曼哈顿距离的
思路:
因为只要全部连在一起
所以谁连谁都可以
用map记所有人的路径
然后随便一个点开始
每次都找最近的连
这样一定可以找到最短的路
自己写了一些干东西
笔记
unordered map的hash value
需要弄运算子==
作为比较时的方法
priority queue 需要
弄运算子>或<
当作greater或less比较的方法
```cpp
struct point
{
int x ;
int y ;
int idx ;
bool operator<(const point& other) const
{
if (x == other.x) return y < other.y;
return x < other.x;
}
bool operator==(const point& other) const {
return x == other.x && y == other.y && idx == other.idx;
}
};
struct point_hash {
std::size_t operator() (const point &p) const {
std::size_t h1 = std::hash<int>{}(p.x);
std::size_t h2 = std::hash<int>{}(p.y);
return h1 ^ (h2 << 1);
}
};
class Solution {
public:
int minCostConnectPoints(vector<vector<int>>& points)
{
unordered_map<point,vector<point> , point_hash> save;
int n = points.size();
for(int i = 0 ; i < n ; i ++)
{
point now;
now.x = points[i][0];
now.y = points[i][1];
now.idx = i;
for(int j = i+1 ; j < n ; j ++){
point next;
next.x = points[j][0];
next.y = points[j][1];
next.idx = j ;
save[now].push_back(next);
save[next].push_back(now);
}
}
point first;
first.x = points[0][0];
first.y = points[0][1];
first.idx = 0;
priority_queue<pair<int,point> , vector<pair<int,point>> , greater<pair<
int,point>> > pq;
pq.push({0,first});
vector<int> passed(n,0);
int nowpass = 0;
int all = 0;
while(!pq.empty())
{
int nowdist = pq.top().first;
point now = pq.top().second;
pq.pop();
if(passed[now.idx])continue;
passed[now.idx] = 1;
all += nowdist;
nowpass ++;
if(nowpass == n)return all;
for(point next : save[now]){
int dist = abs(next.x-now.x) + abs(next.y - now.y);
pq.push({dist,next});
}
}
return all;
}
};
```
作者: cities516 (安安路过)   2024-10-07 14:03:00
大师
作者: MurasakiSion (紫咲シオン)   2024-10-07 14:16:00
最小生成树==
楼主: oin1104 (是oin的说)   2024-10-07 14:17:00
对 我看解答也看到最小生成树

Links booklink

Contact Us: admin [ a t ] ucptt.com