uva 11258 - String Partition

这篇博客讨论了一个编程竞赛中出现的问题,原题要求将字符串拆分为整数并求和,但输入生成错误导致字符串无法直接解析。作者提出了一种改进方法,即寻找最佳分割方式以最大化整数和。提供的C++代码实现了一个动态规划解决方案,遍历所有可能的分割,以找到最大总和。

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

John was absurdly busy for preparing a programming contest recently. He wanted to create a ridiculously easy problem for the contest. His problem was not only easy, but also boring: Given a list of non-negative integers, what is the sum of them?

However, he made a very typical mistake when he wrote a program to generate the input data for his problem. He forgot to print out spaces to separate the list of integers. John quickly realized his mistake after looking at the generated input file because each line is simply a string of digits instead of a list of integers.

He then got a better idea to make his problem a little more interesting: There are many ways to split a string of digits into a list of non-zero-leading (0 itself is allowed) 32-bit signed integers. What is the maximum sum of the resultant integers if the string is split appropriately?

Input

The input begins with an integer N (≤ 500) which indicates the number of test cases followed. Each of the following test cases consists of a string of at most 200 digits.

Output

For each input, print out required answer in a single line.

Sample Input

6

1234554321

5432112345

000

121212121212

2147483648

11111111111111111111111111111111111111111111111111111

Sample Output

1234554321

543211239

0

2121212124

214748372

5555555666

 

题意:将给出的字符串直接拆成若干个int大小内的数,求拆开后获得的数的最大和。

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
int T,len;
char a[550];
long long f[550];
void ready()
{
	//ios::sync_with_stdio(false),cin.tie(0);
	cin>>T;
	return ;
}
void read_in()
{
	scanf("%s",a+1);
	len=strlen(a+1);
	memset(f,0,sizeof(f));

	return ;
}
long long get_sum(int l,int r)
{
	long long re=0;
	for(int i=l;i<=r;i++)
		re=re*10+int(a[i])-'0';
	return re;
}
void do_it()
{
	for(int i=1;i<=len;i++)
	{
		for(int j=1;j<=i;j++)
		{
			long long sum=get_sum(j,i);
			if(sum>=0 && sum<=2147483647)
			{
				 f[i]=max(f[i],f[j-1]+sum);		 
			}
			 
		}
	}
	cout<<f[len]<<endl;
}
int main()
{
	ready();
	while(T--)
	{
		read_in();
		do_it();
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值