任意點~並查集求聯通塊

來源:互聯網
上載者:User

標籤:方向   http   coder   void   algorithm   freopen   turn   name   span   

連結:https://www.nowcoder.com/acm/contest/84/C
來源:牛客網

任意點 時間限制:C/C++ 1秒,其他語言2秒
空間限制:C/C++ 32768K,其他語言65536K
64bit IO Format: %lld
題目描述平面上有若干個點,從每個點出發,你可以往東南西北任意方向走,直到碰到另一個點,然後才可以改變方向。
請問至少需要加多少個點,使得點對之間互相可以到達。輸入描述:
第一行一個整數n表示點數( 1 <= n <= 100)。
第二行n行,每行兩個整數x
i
, y
i
表示座標( 1 <= x
i
, y
<= 1000)。
y軸正方向為北,x軸正方形為東。
輸出描述:
輸出一個整數表示最少需要加的點的數目。
樣本1輸入
22 11 2
輸出
1
樣本2輸入
22 14 1
輸出
0

這個就是一個並查集求聯通快
 1 #include <cstdio> 2 #include <algorithm> 3 #include <vector> 4 #include <queue> 5 #include <cstring> 6 #include <string> 7 using namespace std; 8 const int maxn = 1e4 + 10; 9 10 typedef long long LL ;11 int fa[maxn], x[maxn], y[maxn];12 13 void init(int n) {14     for (int i = 0 ; i <= n ; i++) {15         fa[i] = i;16     }17 }18 int find(int p) {19     while(p != fa[p]) p = fa[p];20     return p;21 }22 int find_set(int p)23 {24     while(p!=fa[p]) p=fa[p];25     return p;26 }27 28 void combine(int p, int q) {29     int np = find_set(p);30     int nq = find_set(q);31     if (np != nq) fa[np] = nq;32 }33 34 int main() {35     int n;36     //freopen("DATA.txt","r",stdin);37     while(scanf("%d", &n) != EOF) {38         init(n);39         for (int i = 1 ; i <= n ; i++) {40             scanf("%d%d", &x[i], &y[i]);41         }42         for (int i = 1 ; i < n ; i++)43             for (int j = i + 1 ; j <= n ; j++)44                 if (x[i] == x[j] || y[i] == y[j] ) combine(i, j);45         int ans = 0;46         for (int i = 1 ; i <= n ; i++)47             if (fa[i] == i) ans++;48         printf("%d\n", ans - 1);49     }50     return 0;51 }

 


任意點~並查集求聯通塊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.