[英]Time Limit Exceeded
对于问题(SPOJ.com-问题FARIDA)。 我正在使用( https://codinghangover.wordpress.com/2014/01/15/spojfarida-princess-farida/ )上给出的相同方法。
以下是我的解决方案==>
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class FARIDA {
public static long maxC(Map<String, Long> map, long c[], int s, int e)
{
if(s>e)
return 0;
if(map.containsKey(s+"|"+e))
return map.get(s+"|"+e);
if(s==e)
map.put(s+"|"+e, c[s]);
else
map.put(s+"|"+e, Math.max(c[s]+ maxC(map,c,s+2,e),maxC(map,c,s+1,e)));
return map.get(s+"|"+e);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int j=1;j<=t;j++)
{
int n=in.nextInt();
long c[]= new long[n];
for(int i=0; i<n; i++)
c[i]=in.nextLong();
Map<String, Long> map = new HashMap<String, Long>();
System.out.println("Case "+j+": "+maxC(map,c,0,n-1));
}
in.close();
}
}
为什么我在Java中获得TLE? 需要什么样的优化? HashMap有什么问题吗?
我认为获得TLE的唯一可能原因是您使用了HashMap,它使用字符串作为键。 因此,当您尝试访问HashMap时,您在浪费时间,并且HashMap将您输入的字符串与HashMap中已经存在的所有键进行匹配。 无需使用HashMap。 您只需使用数组,以数组的索引为键,即可完成所有这些操作。 我已经将map
从HashMap更改为long
数组。
像这样的东西::
public static long maxC(long map[], long coins[], int n) // n is the total number of monsters
{
if(n == 0) // If there are no monsters in the path
return 0;
if(n == 1) // Just in case there is only one monster in the way
return coins[0];
map[0] = coins[0];
map[1] = Math.max(map[0], coins[1]);
for(int i = 2; i < n; i++) {
map[i] = Math.max(map[i-2] + coins[i], map[i-1]);
}
return map[n - 1];
}
在for
循环中,我首先考虑是否只有2个怪物,并在有3个怪物的情况下使用此解决方案,依此类推。
因为现在您不必匹配字符串,所以这大大降低了程序的复杂性。 而且,这里我使用了自下而上的方法,您可以肯定地修改上述方法,并使用自上而下的方法。 尽管我更喜欢自下而上的方法,但是由于我们在这里不进行任何递归调用,因此我相信可以节省一些时间,因为我们没有从栈中推入和弹出函数状态。
编辑::
上下方法:
public static long maxC(long map[], long coins[], int n)
{
if(n-1 < 0)
return 0;
if(map[n - 1] != 0) {
return map[n - 1];
}
map[n - 1] = Math.max(maxC(map, coins, n-2) + coins[n - 1], maxC(map, coins, n-1));
return map[n - 1];
}
在这里,如果没有怪物,我将返回0
,而在map[n-1]
情况下我已经有一个之前计算出的解决方案。
您最初对函数的调用看起来像这样(从main
)::
maxC(map, c, n);
无论如何我们都不需要较低的索引,因此我将其删除。
您可以尝试上述任何一种方法,并且会获得AC。 :D
我认为有一个更好,更简单的方法。 假设我们有一个正整数数组。 我们要做的就是使问题中所说的总和最大化。 要做到这一点
sum
,并将其值和两个相邻的(i + 1和i-1)更改为-1(这样就不再考虑它们了)。 countOfNegOnes==(n-1)
或countOfNegOnes==(n)
。 sum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.