Re: [閒聊] 每日leetcode

看板Marginalman作者 (是oin的說)時間1年前 (2024/10/07 14:02), 編輯推噓1(102)
留言3則, 3人參與, 1年前最新討論串956/1548 (看更多)
每日太水 來寫個不一樣的 題目; 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; } }; ``` -- 邊版的小母雞 — fuckchicken https://i.imgur.com/wglAuYR.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.12.31.156 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1728280938.A.64C.html

10/07 14:03, 1年前 , 1F
大師
10/07 14:03, 1F

10/07 14:16, 1年前 , 2F
最小生成樹==
10/07 14:16, 2F

10/07 14:17, 1年前 , 3F
對 我看解答也看到最小生成樹
10/07 14:17, 3F
文章代碼(AID): #1d0tbgPC (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1d0tbgPC (Marginalman)