您的位置:首页 > 大数据 > 人工智能

Jurassic Remains,NEERC 2003,中途相遇法

2012-11-11 18:09 453 查看
给定n个大写字母组成的字符串,选择尽量多的串,使的每个大写字母都出现偶数次。原题:http://neerc.ifmo.ru/past/2003.html。

参考文献:《算法竞赛入门经典训练指南》P57,刘汝佳

package ProgrammingContest;

import java.util.TreeMap;

public class Jurassic_NEERC_2003 {

public static int count(int X) {
int cnt = 0;
while ( X > 0 ) {
if ( ( X & 0x01 ) != 0 ) cnt++;
X = X >> 1;
}
return cnt;
}

public static int solve(String[] S) {

int N = S.length;
int[] A = new int
;

// first convert strings to integer
for ( int i=0; i<N; i++ ) {
A[i] = 0;
for ( int j=0; j<S[i].length(); j++ ) {
int digit = S[i].charAt(j) - 'A';
A[i] ^= ( 1 << digit );
}
}

// calculate xor result for all combinations
int M = N / 2;
int C = 1 << M;
TreeMap<Integer, Integer> tables = new TreeMap<Integer,Integer>();

for ( int i=0; i<C; i++ ) {
int sum = 0;
for ( int j=0; j<M; j++ ) {
if ( ( i & ( 1 << j ) ) != 0 ) {
sum ^= A[j];
}
}
if ( ! tables.containsKey(sum) || count(tables.get(sum)) < count(i) ) {
tables.put(sum, i);
}
}

int C2 = 1 << ( N - M );
int ans = 0;
for ( int i=0; i<C2; i++ ) {
int sum = 0;
for ( int j=M; j<N; j++ ) {
if ( ( i & ( 1 << (j-M) ) ) != 0 ) {
sum ^= A[j];
}
}
if ( tables.containsKey(sum) && count(tables.get(sum)) + count(i) > count(ans) ) {
ans = ( i << M ) ^ tables.get(sum);
}
}

return ans;
}

public static void printResult(String[] S, int ans) {
System.out.println(count(ans));
int line = 0;
while ( ans != 0 ) {
if ( ( ans & 0x01 ) != 0 ) System.out.printf("%d ",line+1);
line++;
ans >>= 1;
}
System.out.println();
}

/**
* @param args
*/
public static void main(String[] args) {

String[] S = {"ABD","EG","GE","ABE","AC","BCD"};
int ans = solve(S);
printResult(S,ans);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: