POJ-3697(hash+bfs)

bfs

int bfs()
{
	int i;
	queue<int> q;
	q.push(1);
	while (!q.empty()) {
		int index = q.front();
		q.pop();
		visit[index] = 1;
		for (i = 1; i <= a; ++i) {
			if (visit[i]) continue;
			if (!is_exist(index, i))
				q.push(i);
		}
	}
	int ans = 0;
	for (i = 2; i <= a; ++i)
		ans += visit[i];
	return ans;
}
这样会超时,但是

int bfs()
{
	int i;
	queue<int> q;
	q.push(1);
	visit[1] = 1;
	while (!q.empty()) {
		int index = q.front();
		q.pop();
		for (i = 1; i <= a; ++i) {
			if (visit[i]) continue;
			if (!is_exist(index, i)) {
				visit[i] = 1;
				q.push(i);
			}
		}
	}
	int ans = 0;
	for (i = 2; i <= a; ++i)
		ans += visit[i];
	return ans;
}
这样就不会了,我晕啊……

贴个代码,以示惩戒

#define MAXN 100007
#define P 9973
int a, b;
struct edge
{
	int x, y;
} p[1000005];
int next[1000005];
int hash[MAXN];
int visit[10005];
bool is_exist(int x, int y)  
{
	if (x > y) swap(x, y);
    int sum = (x * P + y) % MAXN;
    int index = hash[sum];  
    while (index != -1) {  
        if ((p[index].x == x) && (p[index].y == y))  
            return true;  
        index = next[index];  
    }  
    return false;  
}
int bfs()
{
	int i;
	queue<int> q;
	q.push(1);
	visit[1] = 1;
	while (!q.empty()) {
		int index = q.front();
		q.pop();
		for (i = 1; i <= a; ++i) {
			if (visit[i]) continue;
			if (!is_exist(index, i)) {
				visit[i] = 1;
				q.push(i);
			}
		}
	}
	int ans = 0;
	for (i = 2; i <= a; ++i)
		ans += visit[i];
	return ans;
}
int main()
{
	int i, cases = 1, x, y;
	while (scanf("%d%d", &a, &b) == 2 && (a || b)) {
		memset(hash, -1, sizeof(hash));
		memset(next, -1, sizeof(next));
		memset(visit, 0, sizeof(visit));
		for (i = 0; i < b; ++i) {
			scanf("%d%d", &x, &y);
			if (x > y) swap(x, y);
			p[i].x = x;
			p[i].y = y;
			int sum = (x * P + y) % MAXN;
			next[i] = hash[sum];
			hash[sum] = i;
		}
		printf("Case %d: %d\n", cases++, bfs());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值