gym 101061F. Fairness(dfs或者dp)

本文介绍了一个关于公平分配硬币的问题,目标是最小化分配过程中的不公平因素。通过递归和动态规划两种方法来解决这个问题,并给出了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://codeforces.com/gym/101061/problem/F
题面:

F. Fairness
time limit per test2.0 s
memory limit per test64 MB
inputstandard input
outputstandard output
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.

Example
inputCopy
2
5
1 2 1 4 3
7
4 5 6 1 1 3 4
outputCopy
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


递归写法

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
#define ll long long 
const int N=1e5+100;
const int mod=1000000007;

int a[110];

int sum[110];
int mx;
int n;

void dfs(int pos,int sm,int cnt)
{
	if(cnt>=mx) return ;
	if(pos>=n)
	{
		if(cnt<mx) mx=cnt;
		cnt=0;
		return ;
	}
	int tem=abs(sum[pos]-sm-a[pos] -sm-a[pos] );
	if(tem<mx)
	{
		dfs(pos+1,sm+a[pos],cnt>=tem?cnt:tem);
	}
	if(pos!=0)
	{
		tem=abs(2*sm -sum[pos]);
		if(tem<mx)
		{
			dfs(pos+1,sm,cnt>=tem?cnt:tem);
		}
	}
	return ;
	
		
}
int main()
{
	// freopen("data.in","r",stdin);
	// ios::sync_with_stdio(false);
	// cin.tie(0);
	// cout.tie(0);
	int t;
	//cin>>t;
	scanf("%d",&t);
	
	while(t--)
	{

		//cin>>n;
		scanf("%d",&n);
		mx=0;
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
			if(a[i]>mx) mx=a[i];
			if(i==0) 
				sum[i]=a[i];
			else
				sum[i]=sum[i-1]+a[i];
		}
		dfs(0,0,0);
		//cout<<mx<<endl;
		printf("%d\n",mx);
		
	}
	
	return 0;
}

dp写法



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值