poj2236 Wireless Network(并查集)

本文提供了一种解决POJ-2236问题的C++代码实现方案,通过并查集来判断是否可以成功连接两个点。代码中详细展示了节点结构定义、距离计算、查找和合并操作等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://vjudge.net/problem/POJ-2236

快4s过的,但是排行榜上很多1s内,不知道如何优化。。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<cmath>
 7 #include<stack>
 8 #define lson l, m, rt<<1
 9 #define rson m+1, r, rt<<1|1
10 #define IO ios::sync_with_stdio(false);cin.tie(0);
11 #define INF 0x3f3f3f3f
12 typedef unsigned long long ll;
13 using namespace std;
14 int n, num, d, s, t, pre[10010];
15 char c;
16 typedef struct{
17     int x, y;
18 }Node;
19 Node node[10010];
20 int flag[10010];
21 ll length(ll a, ll b)
22 {
23     return a*a+b*b;
24 }
25 int find(int x)
26 {
27     while(x != pre[x]){
28         x = pre[x];
29     }
30     return x;
31 }
32 void join(int k)
33 {
34     int tx = find(k); 
35     pre[k] = tx;//优化 
36     for(int i = 1; i <= n; i++){
37         if(flag[i]&&i != k){
38             ll tmp = length(node[k].x-node[i].x, node[k].y-node[i].y);
39             if(tmp<=d*d){//一开始直接pre[i]=tx然后wa了,一定要是把根接上去 
40                 int ty = find(i);
41                 pre[i] = ty;//优化 
42                 if(tx != ty){
43                     pre[ty] = tx;
44                 }
45             }
46         }
47     }
48 }
49 int main()
50 {
51     IO;
52     memset(flag, 0, sizeof(flag));
53     cin >> n >> d;
54     for(int i = 1; i <= n; i++){
55         pre[i] = i;
56     }
57     for(int i = 1; i <= n; i++){
58         cin >> node[i].x >> node[i].y;
59     } 
60     while(cin >> c){
61         if(c == 'O'){
62             cin >> num;
63             flag[num] = 1;
64             join(num);
65         }
66         else if(c == 'S'){
67             cin >> s >> t;
68             int tx = find(s);
69             pre[s] = tx; 
70             int ty = find(t);
71             pre[t] = ty;
72             if(tx == ty) cout << "SUCCESS" << endl;
73             else cout << "FAIL" << endl;
74         }
75     }
76     return 0; 
77 }

 

转载于:https://www.cnblogs.com/Surprisezang/p/8994072.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值