[topcoder]FlowerGarden

1.此题很勉强算DP。找了半天网上思路,是个三层的循环,n^3。
2.基本思路就是先找到在第一个位置的花。这样就双层遍历,找到所有和其他不冲突的花中最高的一个,然后放到结果的首位。然后去掉此花,继续使用此方法对余下花朵。
3.要注意的是首先不能直接排序,比如a和b,b和c有冲突,但a和c不一定有冲突。
4.判断两段是否重叠的最简单式子是!(a.start > b.end || b.start > a.end)

思路来自:http://apps.topcoder.com/forums/?module=Thread&threadID=655393&start=0&mc=6#1766488 里面还有一个图形的方法,没仔细看。

public class FlowerGarden {

	public int[] getOrdering(int[] height, int[] bloom, int[] wilt) {

		int len = height.length;

		if (len == 0) return height; // assert length != 0

		int order[] = new int[len];

		boolean used[] = new boolean[len];



		for (int i = 0; i < len; i++) {

			int mxH = 0;

			int pos = -1;

		

			for (int j = 0; j < len; j++) {

				if (used[j]) continue;

				boolean found = true;

				for (int k = 0; k < len; k++) {

					if (used[k]) continue;

					boolean blocking = !(bloom[j] > wilt[k] || bloom [k] > wilt[j]);

					if (height[j] > height[k] && blocking) {

						found = false;

						break;

					}

				}

				if (found) {

					if (height[j] > mxH) {

						mxH = height[j];

						pos = j;

					}

				}

			}

			order[i] = height[pos];

			used[pos] = true;

		}

		return order;

	}

}

  

你可能感兴趣的:(topcoder)