1007 正整數分組
阿新 • • 發佈:2017-09-04
put red printf 數據 fin 方案 個數 限制 logs
1007 正整數分組
基準時間限制:1 秒 空間限制:131072 KB 分值: 10 難度:2級算法題
將一堆正整數分為2組,要求2組的和相差最小。 例如:1 2 3 4 5,將1 2 4分為1組,3 5分為1組,兩組和相差1,是所有方案中相差最少的。Input
第1行:一個數N,N為正整數的數量。 第2 - N+1行,N個正整數。 (N <= 100, 所有正整數的和 <= 10000)
Output
輸出這個最小差
Input示例
5
1
2
3
4
5
Output示例
1
//題解:因為數據範圍極小,所以是dp的簡單變動,先算出可以組成哪些數,然後,枚舉一下所有情況即可
1 #include<iostream> 2 #include<cmath> 3 #include<cstring> 4 #include<algorithm> 5 #include<cstdio> 6 #include<vector> 7 using namespace std; 8 #define INF 0x3f3f3f3f 9 #define N 1005 10 11 int num[N]; 12 int dp[10005]; 13 14 int main() 15 {View Code16 int n; 17 scanf("%d",&n); 18 int all=0; 19 for (int i=1;i<=n;i++) 20 { 21 scanf("%d",&num[i]); 22 all+=num[i]; 23 } 24 int ut = all/2; 25 dp[0]=1; 26 for (int i=1;i<=n;i++) 27 { 28 for (int j=ut;j>=num[i];j--)29 { 30 if (dp[j-num[i]]) dp[j]=1; 31 } 32 } 33 int ans = INF; 34 for (int i=1;i<=ut;i++) 35 { 36 if (dp[i]) ans=min(ans,(all-i)-i); 37 } 38 printf("%d\n",ans); 39 return 0; 40 }
1007 正整數分組