传送门:Gym 101061F
Problem Description
Dwik and his brother Samir both received scholarships from a famous university in India. Their father, Besher, wants to send some money with each of them.
Besher has n coins, the ith coin has a value of ai. He will distribute these coins between his two sons in n steps. In the ith step, he chooses whether to give the ith coin to Dwik or to Samir.
Let xi be the absolute difference between the sum of Dwik’s and Samir’s coins after the ith step. The unfairness factor of a distribution is max({x1, x2, …, xn}). Besher wants to minimize the unfairness factor, can you help him?
Input
The first line of the input consists of a single integer t, the number of test cases. Each test case consists of 2 lines:
The first line contains an integer n (1 ≤ n ≤ 100).
The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 100).
Output
Print t lines, ith line containing a single integer, the answer to the ith test case.
Sample Input
2
5
1 2 1 4 3
7
4 5 6 1 1 3 4
Sample Output
2
5
Note
In the first sample test, besher has 5 coins (1, 2, 1, 4, 3), he can distribute them in the following way:
Step 1: Give the first coin to dwik , d = 1, s = 0 => x1=|1 - 0|=1
Step 2: Give the second coin to samir, d = 1, s = 2 => x2=|1 - 2|=1
Step 3: Give the third coin to samir, d = 1, s = 3 => x3=|1 - 3|=2
Step 4: Give the fourth coin to dwik, d = 5, s = 3 => x4=|5 - 3|=2
Step 5: Give the fifth coin to samir, d = 5, s = 6 => x5=|5 - 6|=1
max({x1, x2, x3, x4, x5}) = 2
题意:
给定n个权值,按序做n次选择,
每次选择把该权值分配给A或B,
其最终的权值既是在决策过程中A和B差值绝对值的最大值,
我们的目标是使这个函数最小化.输出最小权值.
题解:
当时做的时候想用dp做,但是状态怎么转移我一直想不出来,就看到他的n的范围也不是很大,就想有dfs做。
直接做交上去后超时了。然后就想到了剪枝,每次只要该行的差大于当前最大值了,就直接退出。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=110000;
int t;
int n;
int a[110];
int maxn;
void dfs(int x,int m,int s,int d)
{
if(m>=maxn)
return ;
if(x>=n)
{
maxn=m;
return;
}
if(abs(s-d)>m) m=abs(s-d);
dfs(x+1,m,s+a[x],d);
dfs(x+1,m,s,d+a[x]);
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
maxn=inf;
dfs(1,0,a[0],0);
printf("%d\n",maxn);
}
return 0;
}