洛谷P2906 [USACO08OPEN]牛的街区Cow Neighborhoods

洛谷P2906 [USACO08OPEN]牛的街区Cow Neighborhoods

曼哈顿距离转切比雪夫距离

 1 #include <bits/stdc++.h>
 2 #define LL long long 
 3 #define GG int
 4 #define For(i, j, k) for(register int i=j; i<=k; i++)
 5 #define Dow(i, j, k) for(register int i=j; i>=k; i--)
 6 using namespace std;
 7 GG read() {
 8     GG x = 0, f = 1;
 9     char ch = getchar();
10     while(ch<'0'||ch>'9') { if(ch=='-') f = -1; ch = getchar(); }
11     while(ch>='0'&&ch<='9') { x = x*10+ch-48; ch = getchar(); }
12     return x * f;
13 }
14 void write(GG x) {
15     if(x<0) putchar('-'), x = -x;
16     if(x>9) write(x/10);
17     putchar(x%10+48);
18 }
19 void writeln(GG x) { write(x); putchar('\n'); }
20 
21 const int N = 100011; 
22 struct node{
23     LL x,y; 
24     int id; 
25 }a[N];
26 int n,C, Mx, ans;
27 int fa[N], tot[N];  
28 multiset<node> s;
29 multiset<node> ::iterator it;
30 
31 bool cmp_x(node a, node b) { return a.x < b.x; } 
32 bool operator <(node a,node b) { 
33     return a.y < b.y; 
34 }
35 
36 int find(int x) {
37     if(fa[x] == x) return x; 
38     return fa[x] = find(fa[x]); 
39 }
40 
41 void Union(int x, int y) {
42     x = find(x); y = find(y); 
43     if(x==y) return; 
44     if(tot[x] < tot[y]) swap(x, y); 
45     fa[y] = x; tot[x] += tot[y];
46     --ans; 
47 }
48 
49 void work() {
50     sort(a+1, a+n+1, cmp_x);
51     int h = 1; 
52     s.insert(a[1]); 
53     s.insert( (node){0ll, 1e10, 0 } ); 
54     s.insert( (node){0ll, -1e10, 0 } ); 
55     For(i, 2, n) {
56         while(a[i].x-a[h].x > C) s.erase( s.find(a[h]) ), ++h; 
57         it = s.lower_bound(a[i]); 
58         node p = *it; 
59         if(p.y-a[i].y <= C) Union(a[i].id, p.id); 
60         --it; p = *it; 
61         if(a[i].y-p.y <= C) Union(a[i].id, p.id); 
62         s.insert(a[i]); 
63     }
64 }
65 
66 int main() {
67     n = read(); C = read(); 
68     For(i, 1, n) {
69         int x=read(), y=read(); 
70         a[i].x = x+y; a[i].y=x-y; 
71         a[i].id = i; 
72     }
73     For(i, 1, n) fa[i] = i, tot[i]=1; 
74     ans = n; 
75     work(); 
76     For(i, 1, n) Mx = max(Mx, tot[i]); 
77     printf("%d %d\n", ans, Mx); 
78     /*
79     For(i, 1, n) fa[i] = find(fa[i]); 
80     sort(fa+1, fa+n+1); 
81     fa[0] = fa[1]+1; 
82     int num = 0, len = 0, Mx = 0; 
83     For(i, 1, n) 
84         if(fa[i] != fa[i-1]) {
85             if(len > Mx) Mx = len; 
86             len = 1;
87             ++num; 
88         }
89         else ++len; 
90     if(len>Mx) Mx = len; 
91     printf("%d %d\n", num, Mx); 
92     */
93 }

 

posted @ 2018-02-24 11:13  third2333  阅读(162)  评论(0编辑  收藏  举报