TopCoder SRM 582 SpaceWarDiv2


算法复杂度:O(m+n)(假定girl和enemy都有序,实际题目,不记得,如果不是有序,那么先排序,采用计数排序的话,如果范围不大还可以进一步减小算法复杂度)

O(MlogM+nlogN)

 

 

 

实际过程是:采用归并排序过程中合并计算移动平均数

 

public class SpaceWarDiv1 {


	/**
	 * 实际上是求移动平均数(实际计算只需要2个变量,而不是sum变量个数)
	 * ai表示第i个girl,bj表示第i个enemy
	 * 用sum[i]表示倒数第i个girl能打死的enemy总数sum[0]表示最强girl可以打死的人数
	 * 实际求的是max{sum[0],sum[0:1]/2,sum[0:3]/3.....
	 * @param magicalGirlStrength
	 * @param enemyStrength
	 * @param enemyCount
	 * @return
	 */
	public long minimalFatigue(int[] magicalGirlStrength, int[] enemyStrength, long[] enemyCount)
	{		
		int i=magicalGirlStrength.length-1;
		int j = enemyStrength.length-1;
		if(enemyStrength[j]>magicalGirlStrength[i])
			return -1L;
		
		long sum[]=new long[2];
		sum[0]=0;
		sum[1]=0;
		long maxVal = 0;
		int count=0;
		while(i>=0&&j>=0)
		{
			while(i>=0 && magicalGirlStrength[i]>=enemyStrength[j]) i--;
			if(i<0) break;
			while(j>=0&&magicalGirlStrength[i]=enemy;calc last gir sum
				
				//sum[i+1]
				{
					//average
					count = magicalGirlStrength.length-i-1;
					long average = (sum[1]+sum[0]+count-1)/(count);
					maxVal = (maxVal>average)?maxVal:average;
				}
				sum[0] = sum[0]+sum[1];
				sum[1]=0;
		}
		
		while(j>=0){
			sum[1] += enemyCount[j];
			j--;
		}
		{
			//average
			count = magicalGirlStrength.length-i-1;
			long average = (sum[1]+sum[0]+count-1)/count;
			maxVal = (maxVal>average)?maxVal:average;
		}
		
		return maxVal;
	}
	public static void main(String args[])
	{
		int []magicalGirlStrength=new int[]{2,3,5};
		 int[] enemyStrength = new int[]{1,3,4};
		 long[] enemyCount =new long[]{2,9,4};
	 
//			int []magicalGirlStrength=new int[]{2,3,5};
//			 int[] enemyStrength = new int[]{1,1,2};
//			 long[] enemyCount =new long[]{2,9,4};
		 System.out.println(new SpaceWarDiv1().minimalFatigue(magicalGirlStrength, enemyStrength, enemyCount));
		
	}
}

 

 

你可能感兴趣的:(TopCoder)