广度优先懵逼VS深度优先懵逼

import java.util.ArrayList;

public class Test {
	
	public static void main(String[] arg0) {
		String answer = "12<alter=3*4>5<alter=6*7*8>9";
		ArrayList<String> answers = new ArrayList<String>();
		if (answer.indexOf("<alter=") >= 0) {
			int i;
			ArrayList<ArrayList<String>> parts = new ArrayList<ArrayList<String>>();
			while ((i = answer.indexOf("<alter=")) >= 0) {
				ArrayList<String> string = new ArrayList<String>();
				string.add(answer.substring(0, i));
				parts.add(string);
				answer = answer.substring(i + 7);
				int j = answer.indexOf(">");
				try {
					String alter = answer.substring(0, j);
					String[] alternatives = alter.split("[*]");
					ArrayList<String> alternative = new ArrayList<String>();
					for (int k = 0; k < alternatives.length; k ++) alternative.add(alternatives[k]);
					parts.add(alternative);
					answer = answer.substring(j + 1);
				} catch (IndexOutOfBoundsException e) {
					break;
				}
			}
			ArrayList<String> string = new ArrayList<String>();
			string.add(answer);
			parts.add(string);
			//广度优先懵逼
			for (i = 0; i < multiplicativeSize(parts, 0, parts.size()); i ++) answers.add("");
			for (i = 0; i < parts.size(); i ++) {
				for (int j = 0; j < multiplicativeSize(parts, 0, i + 1); j ++) {
					for (int k = 0; k < multiplicativeSize(parts, i + 1, parts.size()); k ++) {
						int targetIndex = j * multiplicativeSize(parts, 0, parts.size()) /
								multiplicativeSize(parts, 0, i + 1) + k;
						int sourceIndex = j % parts.get(i).size();
						answers.set(targetIndex, answers.get(targetIndex) + parts.get(i).get(sourceIndex));
					}
				}
			}
			//打印并清空
			for (int j = 0; j < answers.size(); j ++) System.out.println(answers.get(j));
			System.out.println("");
			answers.clear();
			//深度优先懵逼
			i = multiplicativeSize(parts, 0, parts.size());
			for (int j = 0; j < i; j ++) {
				answers.add("");
				for (int k = 0; k < parts.size(); k ++) 
					answers.set(j, answers.get(j) + parts.get(k).get(j % parts.get(k).size()));
			}
		} else answers.add(answer);
		for (int j = 0; j < answers.size(); j ++) System.out.println(answers.get(j));
	}
	
	static int multiplicativeSize(ArrayList<ArrayList<String>> arrayList, int beginIndex, int endIndex) {
		int result = 1;
		if (beginIndex < endIndex)
			for (int i = beginIndex; i < endIndex; i ++) result *= arrayList.get(i).size();
		return result;
	}
}

这次应该是深度优先懵逼赢了。

顺带一提,广度优先懵逼的思路是法语课上想出来的,结果下课后思路断了,晚上和一个同学一起搞了两个小时才把思路重新理清。深度优先懵逼是选修课考试时用多出的时间手写的,一次就写成了。

运行结果如下:

123569
123579
123589
124569
124579
124589


123569
124579
123589
124569
123579
124589

展开阅读全文

没有更多推荐了,返回首页