【BZOJ1098】[POI2007]办公楼biu【BFS/DFS】【链表优化】【补图】

求补图的联通块个数...


发现链表原来还可以这么玩...


听说DFS会超时。


/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 100005, maxm = 2000005, maxq = maxn;

int n, m, head[maxn], cnt, pre[maxn], suf[maxn], q[maxq], tot, size[maxn];
bool vis[maxn];

struct _edge {
	int v, next;
} g[maxm << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v) {
	g[cnt] = (_edge){v, head[u]};
	head[u] = cnt++;
}

inline void del(int x) {
	int t = pre[x];
	suf[t] = suf[x];
	pre[suf[x]] = t;
}

inline void bfs(int x) {
	int h = 0, t = 0; q[t++] = x;
	while(h != t) {
		size[tot]++;
		int u = q[h++];
		for(int i = head[u]; ~i; i = g[i].next) vis[g[i].v] = 1;
		for(int i = suf[0]; i; i = suf[i]) if(!vis[i]) del(i), q[t++] = i;
		for(int i = head[u]; ~i; i = g[i].next) vis[g[i].v] = 0;
	}
}

int main() {
	n = iread(); m = iread();
	for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;

	for(int i = 1; i <= m; i++) {
		int x = iread(), y = iread();
		add(x, y); add(y, x);
	}

	for(int i = 0; i <= n; i++) pre[i] = i - 1, suf[i] = i + 1;
	pre[0] = suf[n] = 0;

	for(int i = suf[0]; i; i = suf[0]) {
		del(i);
		tot++;
		bfs(i);
	}

	sort(size + 1, size + 1 + tot);
	printf("%d\n%d", tot, size[1]);
	for(int i = 2; i <= tot; i++) printf(" %d", size[i]);

	return 0;
}


你可能感兴趣的:(优化,链表,DFS,bfs,联通块)