0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Atcoder解いてみた AtCoder Beginner Contest D - Index × A(Not Continuous ver.)

0
Posted at

AtCoder Beginner Contest D - Index × A(Not Continuous ver.)

問題はこちら

回答

明らかにDPというのは分かった
ただ、状態の設計が甘く、WA,,,
以下、解説を見つつ直したコード

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <limits.h>
#include <bitset>
#include <list>
#include <set>
#include <numeric>
#include <tuple>
#include <iomanip>
#include <random>

int N, M;
std::vector<long long> A;

int main()
{
	std::cin.tie(0);
	std::ios::sync_with_stdio(false);

	std::cin >> N >> M;

	A.resize(N+1);
	for (int i = 1; i <= N; i++) {
		std::cin >> A[i];
	}

	

	long long inf = 1e18;
	// [i][j] : i番目まで見たときに、j個とっているときの最大値
	// 負の値は取らないほうがいい→いや、そんなことない最終的に増えるならとっていい(Biにかける係数が増える) 多少損してもいい
	// 部分列の後の方が、スコアに与える影響あるので、影響度の大きいものから決めていこうと思ったがそんな必要は無い
	// 単純な最大化問題なので、初期値を十分に小さくしておき、DPにより、目先の損をしても、最後にスコアを最大化できるように処理していけばいい
	std::vector<std::vector<long long>> dp = std::vector<std::vector<long long>>(N+1, std::vector<long long>(M+1, -inf));

	// j=0個の時、スコアは0
	for (int i = 0; i <= N; i++) {
		dp[i][0] = 0;
	}

	// i番目
	for (int i = 1; i <= N; i++) {
		// j個選択する場合(M個まで選択できる)
		for (int j = 1; j <= M; j++) {

			// iを選択しない(j個選択するループであることに注意)
			long long notSelect = dp[i-1][j];
			// iを選択(後ろからi-1まで見た,j-1個選択→後ろからiまで見た,j個選択)
			long long select = dp[i-1][j-1] + j*A[i];

			// iを選択しない
			// iを選択しないが、iまで見たので更新はする(j個選択するループであることに注意)
			dp[i][j] = notSelect;

			// iを選択
			// 安全のために、dp[i - 1][j - 1]に値が入っていないときは除外
			if (dp[i - 1][j - 1] != -inf) {
				// iまで見て、j個を選択
				dp[i][j] = std::max(select, notSelect);
			}
		}
	}

	std::cout << dp[N][M] << std::endl;

	return 0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?