Gym - 100703G-G-Game of numbers-暴力

本文介绍了一种算法,用于在给定的一系列整数中,找到包含正负号的最长连续合法序列,并输出该序列及其符号表示。通过遍历序列并根据相邻元素的正负性进行合法性判断,最终确定序列的长度和符号。

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

给出n个数。。。初始值为零 对每一个数赋一个正或负号。使得,每次操作的值在【0,k】之间

输出最长的符号长度 及其符号

对每一个数 判断其正负数+前一个数(遍历)是否合法,如果合法且正 a[i]+x 标记为1,负标记为-1;

最后找到最后一个数,往前一直推即可得答案 



#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <vector>
using namespace std;
 
int a[1005][1005]; 
int  c[1005];
char ans[1005];
int main()
{   
	int n,k; 
	scanf("%d%d",&n,&k);
	int i,j;
	int tmp;


	for (i=1;i<=n;i++)
	{
		scanf("%d",&tmp);
		c[i]=tmp; 
	}
	a[1][c[1]]=1;
	for (i=2;i<=n;i++)
	{
		int cnt=0;
		for (j=0;j<=1000;j++)
		{
			if (a[i-1][j])
			{
				if (j+c[i]<=k)
				{
					a[i][j+c[i]]=1;
					cnt=1;
				}
				if (j-c[i]>=0)
				{
					a[i][j-c[i]]=-1;
					cnt=1;

				}

			}
		}
		if (cnt==0)break;
	}


	

		int mark=i-1;  //最长长度
		i--;
		printf("%d\n",mark);
		for (j=0;j<=1000;j++)
		{
			if (a[mark][j]==1)
			{
				ans[mark]='+';
				break;
			}
			else
				if (a[mark][j]==-1)
			{
				ans[mark]='-';
				break;
			}

		}
		i=j;
		if (ans[mark]=='+')
			i-=c[mark];
		else
			i+=c[mark];
 
		for (j=mark-1;j>=1;j--)
		{
			if (a[j][i]==1)
			ans[j]='+';
			else
				ans[j]='-';
			if (a[j][i]==1)
				i-=c[j];
			else
				if (a[j][i]==-1)
				i+=c[j];

			
		}

	for (i=1;i<=mark;i++)
	{
		printf("%c",ans[i]);
	}
	cout<<endl;
	
	
	
	
	return 0;
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值