我一直在ACM上向這個問題提交程序。 Problem ID=1922但我的解決方案不斷得到時間超出限制上測試3除了這個暴力破解方法之外的任何更快的解決方案
我的想法是使用蠻力但也有一些分支,切斷。下面是我的Java代碼,任何更快的解決方案或改進將不勝感激...我想這並不難,因爲難度只有195,但我不能接受。
終於被接受了。該算法首先對英雄進行排序,並首先從最小願望開始。只是爲O(n)..
我的Java代碼是迄今爲止速度最快的Solution Rank
非常感謝!
public class testtest
{
static boolean[] used;
// length of heros
static int ulen;
// list of heros
static Wish[] w;
// number of possible teams
static int count = 0;
// and output
static StringBuilder str = new StringBuilder();
// add the team
// check if it is a valid team
static boolean check(int len)
{
for (int i = 0; i < ulen; i ++)
{
if (!used[i])
{
// adding another hero makes it reliable, so invalid
if (w[i].wish <= len + 1)
{
return false;
}
}
}
return true;
}
// search the teams, team size = total, current pick = len, start from root + 1
static void search(int root, int total, int len)
{
if (len >= total) // finish picking len heros
{
if (check(total)) // valid
{
print(total); // add to output
}
return;
}
for (int i = root + 1; i < ulen; i ++)
{
if (w[i].wish > len + ulen - i)
{
return; // no enough heros left, so return
}
else
if (w[i].wish <= total) // valid hero for this team
{
used[i] = true;
search(i, total, len + 1); // search next hero
used[i] = false;
}
}
}
public static void main(String[] args) throws IOException
{
BufferedReader rr = new BufferedReader(new InputStreamReader(System.in));
ulen = Integer.parseInt(rr.readLine());
w = new Wish[ulen];
for (int i = 0; i < ulen; i ++)
{
w[i] = new Wish(i + 1, Integer.parseInt(rr.readLine()));
}
Arrays.sort(w);
used = new boolean[ulen];
Arrays.fill(used, false);
for (int i = 1; i <= ulen; i ++)
{
for (int j = 0; j <= ulen - i; j ++)
{
if (w[j].wish <= i) // this hero is valid
{
used[j] = true;
search(j, i, 1);
used[j] = false;
}
}
}
System.out.println(count);
System.out.print(str);
}
}
你可能想看一看組合數學。 – bdares
我認爲該算法仍然基於搜索,因爲整個列表需要打印,而不僅僅是答案的總數。 –
與算法無關,但在StringBuffer.append調用中更改'+'將肯定會縮短一些時間。 –