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;
}