您的位置:首页 > 其它

《算法竞赛-训练指南》第一章-1.25-LA 2965

2013-08-04 10:23 573 查看
题目中的描述是这样的,选取最多的元组使得所选取的元组中的相同的字母的个数为偶数。

刚开始用的枚举,明显有点暴力了,但看到时限那么长,就试了试,超时。

但是好像也不像超时的样子呀,2^24 = 16777216 * 24 = 4亿哇,也不会超过18S哇。诶,不知道是怎么回事,反正是过不了。

题解中介绍的方法是,中途相遇法。也就是利用如果有结果的话,必定是两个相等的数异或,所以,先把前面的N/2个结果存起来,然后在后面的N/2个中查找,这样速度就会直线下降,首先2^24 编程了2^12次方,然后再成上个查找的时间log(n)这根本就不算什么,所以枚举就超过了18S,但是用这种半路相遇法,才32MS,这速率非常的直观!

其实这种方法自己是见过的,就是那种给你几行数,然后让你在每行中选一个数,使得达到某个条件。比如最大,最小了,什么的。这种就需要分成几部分,然后分别求解,最后和起来的结果就是你所求的。

贴出超时的枚举代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

int N;

char str[1111];

int A[33];

int check(int x, int *B)
{
int c[33];
int cnt = 0;
for (int i = 0; i < N; i++)
{
if ((1 << i) & x)
{
c[cnt] = A[i];
B[cnt++] = i;
}
}
int temp = 0;
for (int i = 0; i < cnt; i++)
{
temp ^= c[i];
}
if (temp == 0)
{
return cnt;
}
else
{
return 0;
}
}

int main()
{
while (scanf("%d", &N) != EOF)
{
memset(A, 0, sizeof(A));
for (int i = 0; i < N; i++)
{
scanf("%s", str);
int len = strlen(str);
for (int j = 0; j < len; j++)
{
A[i] ^= (1 << (str[j] - 'A'));
}
// cout << "A[i] = " << A[i] << endl;
}
int ans = 0;
int B[33];
int C[33];
for (int i = 0; i < (1 << N); i++)
{
int temp = check(i, B);
if (ans < temp)
{
ans = temp;
for (int j = 0; j < ans; j++)
{
C[j] = B[j];
}
}
}
printf("%d\n", ans);
for (int i = 0; i < ans; i++)
{
printf(i == 0 ? "%d" : " %d", C[i] + 1);
}
printf("\n");
}
// system("pause");
return 0;
}


然后是半路相遇法:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <map>
#include <algorithm>

using namespace std;

const int MAXN = 24 + 2;

int N;

char str[1111];

int A[MAXN];

map <int, int> table;

int bitcount(int x)
{
return x == 0 ? 0 : bitcount(x >> 1) + (x & 1);
}

int main()
{
while (scanf("%d", &N) != EOF)
{
if (N == 0)
{
break;
}
for (int i = 0; i < N; i++)
{
scanf("%s", str);
int len = strlen(str);
A[i] = 0; //这个实在是太重要了
for (int j = 0; j < len; j++)
{
A[i] ^= (1 << (str[j] - 'A')); //千万要注意低级错误 为什么要用^呢,因为单词中可以出现相同的字母
}
}
table.clear();
int n1 = N / 2;
int n2 = N - n1;
for (int i = 0; i < (1 << n1); i++) //i要从0开始,这也是一个陷阱,如果从1开始的话,就有一个单词是处理不了的.
{
int x = 0;
for (int j = 0; j < n1; j++)
{
if ((1 << j) & i)//选择了第j个
{
x ^= A[j];
}
}
if (!table.count(x) || bitcount(table[x]) < bitcount(i))//如果再table表里面没有x或者如果有了,但是新找到的含有的
{ //元组更多一些
table[x] = i;
}
}
int ans = 0;
for (int i = 0; i < (1 << n2); i++)
{
int x = 0;
for (int j = 0; j < n2; j++)
{
if ((1 << j) & i)
{
x ^= A[n1 + j];
}
}
if (table.count(x) && bitcount(ans) < bitcount(table[x]) + bitcount(i))
{
ans = (i << n1) ^ table[x];
}
}
printf("%d\n", bitcount(ans));
int flag = 0;
for (int i = 0; i < N; i++)
{
if ((1 << i) & ans)
{
if (flag == 0)
{
printf("%d", i + 1);
flag = 1;
}
else
{
printf(" %d", i + 1);
}
}
}
printf("\n");
}
// system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: