POJ 1944 Fiber Communications (枚举 + 并查集 OR 线段树)

题意

在一个有N(1 ≤ N ≤ 1,000)个点环形图上有P(1 ≤ P ≤ 10,000)对点需要连接。连接只能连接环上相邻的点。问至少需要连接几条边。

思路

突破点在于最后的结果一定不是一个环!所以我们枚举断边,则对于P个连接要求都只有唯一的方法:如果一个pair的两个端点在断点两侧,就分成[0,left],[right,N];否则就是[left, right]。这里区间以0开头是要考虑left=1、right=N的情况,至少得有个边([0, 1])表示N连向1的情况不是么。 处理一个区间内相连情况通常可以用线段树。不过我在这里用了下并查集,也挺有意思的:每个并查集的父节点是它连接着的最右端的节点,并且维护一个数量集。然后连接[x, y]的时候直接找x的父节点(最右点),再挨个向右缩点直到y即可

代码

  [cpp] #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <string> #include <cstring> #include <vector> #include <set> #include <stack> #include <queue> #define MID(x,y) ((x+y)/2) #define MEM(a,b) memset(a,b,sizeof(a)) #define REP(i, begin, end) for (int i = begin; i <= end; i ++) using namespace std; struct P{ int a, b; }p[10005]; const int MAXN = 1005; struct Disjoint_Sets{ struct Sets{ int father, num; }S[MAXN]; void Init(int n){ for (int i = 0; i <= n; i ++){ S[i].father = i; S[i].num = 1; } } int Father(int x){ if (S[x].father == x){ return x; } else{ S[x].father = Father(S[x].father); //Path compression return S[x].father; } } void Union(int x, int y){ int fx = Father(x), fy = Father(y); S[fy].num += S[fx].num; S[fx].father = fy; } }DS; void uni(int x, int y){ int xx = DS.Father(x); while(DS.Father(xx) != DS.Father(y)){ DS.Union(xx, xx+1); xx = DS.Father(xx); } } int main(){ //freopen("test.in", "r", stdin); //freopen("test.out", "w", stdout); int n, m; scanf("%d %d", &n, &m); for (int i = 0; i < m; i ++){ scanf("%d %d", &p[i].a, &p[i].b); if (p[i].b < p[i].a) swap(p[i].b, p[i].a); } int res = 0x3fffffff; for (int l = 1; l <= n; l ++){ DS.Init(n); for (int i = 0; i < m; i ++){ if (p[i].a <= l && p[i].b >= (l+1)%n){ uni(0, p[i].a); uni(p[i].b, n); } else uni(p[i].a, p[i].b); } int sum = 0; bool vis[1005] = {0}; for (int i = 1; i <= n; i ++){ if (!vis[DS.Father(i)] && DS.S[DS.Father(i)].num > 1){ sum += DS.S[DS.Father(i)].num - 1; vis[DS.Father(i)] = 1; } } res = min(res, sum); } printf("%d\n", res); return 0; } [/cpp]
posted @ 2013-10-01 15:38  AbandonZHANG  阅读(264)  评论(0编辑  收藏  举报