2014-10-16 38 views
0

我給出了N個元素及其權重,而且我只需從中選取其中的M個元素,使得它們的權重除以k。將一個元素劃分成一個組

For Ex: 
N=5 
Weight:1 2 3 4 5 
M =3 
K=5 
so we will pick up : 1 4 5 as total 10 is divide by 5. So ans =10 

我的方法:使用遞歸函數

public static int ans(int[] a,int m,int k,int total){ 
     int sum=0; 
     if(a.length<m) 
     return Integer.MAX_VALUE; 
     if(m==0){ 
      //System.out.println("ok"); 
      if(total%k==0) 
       return total; 
      else 
       return Integer.MAX_VALUE; 
     } 
     int[] temp = new int[a.length-1]; 
     for(int j=0;j<temp.length;j++) 
      temp[j]=a[j]; 

     sum = Math.min(ans(temp,m,k,total), ans(temp,m-1,k,total+a[a.length-1])); 




     return sum; 
    } 

但這種方法失敗的數據量非常大的,有人可以幫助我如何使用動態規劃在此,讓我不t重複呼叫。

+0

我的要求並不清楚。前三個元素(權重爲1,1和3)呢?他們也加起來重量5.通常,有不止一種可能的解決方案。另外,可能沒有解決辦法。你的算法應該提供什麼?我也看到,你只返回一個int。這怎麼可能是一個解決方案? – Seelenvirtuose 2014-10-16 11:07:40

+0

@Seelenvirtuose [鏈接](http://www.codechef.com/problems/BUYING) – user4116864 2014-10-16 11:12:00

+0

如何將輸入值按其餘模'K'分組? – CiaPan 2014-10-16 11:55:56

回答

0

獲取一個標記數組,標記每個元素是否包含在結果中。從包含任何東西開始,如果包含它可以提供正確的結果,則遞歸地嘗試每個元素。

相關問題