hdu 4223 Dynamic Programming?(최소 연속 서브 시퀀스 절대 값 과)

1730 단어 dp
http://acm.hdu.edu.cn/showproblem.php?pid=4223
연속 서브 시퀀스 의 합 을 구 하 는 절대 값 최소 값
이 문 제 는 정말 실 패 했 습 니 다. 왜 dp [i] 로 i 까지 절대 치 최소 치 를 표시 하 는 지 모 르 겠 습 니 다. WA 는 n 번 입 니 다.그냥 폭력 으로..
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cmath>
using namespace std;
const int INF = 0x3f3f3f3f;
int ans;
int main()
{
    int test;
    scanf("%d",&test);
    for(int item = 1; item <= test; item++)
    {
        int n,a[1010];
        scanf("%d",&n);
        for(int i = 1; i <= n; i++)
            scanf("%d",&a[i]);

		ans = abs(a[1]);

		for(int i = 1; i <= n; i++)
		{
			int sum = 0;
			for(int j = i; j <= n; j++)
			{
				sum += a[j];
				if(ans > abs(sum))
					ans = abs(sum);
			}
		}
		printf("Case %d: %d
",item,ans); } return 0; }

그래도 돼...?
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cmath>
using namespace std;
const int INF = 0x3f3f3f3f;
int ans;
int main()
{
    int test;
	int n,a[1010],sum[1010];

    scanf("%d",&test);
    for(int item = 1; item <= test; item++)
    {
        scanf("%d",&n);
        ans = INF;
        sum[0] = 0;	
        for(int i = 1; i <= n; i++)
		{
			scanf("%d",&a[i]);
			sum[i] = sum[i-1]+a[i]; // 1~i  
			if(ans > abs(sum[i]))
				ans = abs(sum[i]);
		}

		for(int i = 2; i <= n; i++)
		{
			for(int j = 1; j < i; j++)
			{ //       ,       
				if(ans > abs(sum[i]-sum[j]))
					ans = abs(sum[i]-sum[j]);
			}
		}

		printf("Case %d: %d
",item,ans); } return 0; }

좋은 웹페이지 즐겨찾기