POJ 3274.Gold Balanced Lineup

题目:http://poj.org/problem?id=3274

AC代码(C++):

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define INF 0xfffffff
#define MAXN 100005
#define prime 99991

using namespace std;

struct NODE{
	int num;
	int next;
};

NODE node[MAXN];
int hash[MAXN];
int n,k,cnt;
int feature[MAXN][31];
int sum[MAXN][31];
int c[MAXN][31];

bool cmp(int a, int b){
	for(int i = 0; i < k; i++){
		if(c[a][i]!=c[b][i])return false;
	}
	return true;
}

int getHash(int num){
	int rtn = 0;
	for(int i = 0; i < k; i++){
		rtn += (c[num][i]*i)%prime;
	}
	return abs(rtn)%prime;
}

void insertHash(int num, int key){
	node[cnt].num = num;
	node[cnt].next = hash[key];
	hash[key] = cnt;
	cnt++;
}

int searchHash(int num){
	int key = getHash(num);
	int next = hash[key];
	while(next!=-1){
		if(!cmp(num,node[next].num)){
			next = node[next].next;
		}
		else return node[next].num;
	}
	insertHash(num,key);
	return -1;
}

int main(){
	cin>>n>>k;
	cnt = 0;
	for(int i = 0; i < prime; i++)hash[i] = -1;
	for(int i = 0; i < k; i++)c[0][i] = 0;
	searchHash(0);
	int maxlen = 0;
	for(int i = 0; i < n; i++){
		int tmp;
		cin>>tmp;
		
		for(int j = 0; j < k; j++){
			feature[i+1][j] = tmp%2;
			tmp/=2;
		}
		
		if(i==0){
			for(int j = 0; j < k; j++)sum[1][j] = feature[1][j];
		}
		else{
			for(int j = 0; j < k; j++)sum[i+1][j] = sum[i][j]+feature[i+1][j];
		}
		
		for(int j = 0; j < k; j++)c[i+1][j] = sum[i+1][j]-sum[i+1][0];
		
		int index = searchHash(i+1);
		if(index!=-1&&i+1-index>maxlen)maxlen=i+1-index;
	}
	cout<<maxlen;
}
总结: 把问题转换成哈希查找就好做了, 具体转换参照官方解题报告, 具体做法看这里:

http://www.cnblogs.com/lyy289065406/archive/2011/07/30/2122224.html

转换好了后就是普通的数字哈希了.

你可能感兴趣的:(poj)