dp greedy math *1800

Please click on ads to support us..

C++ Code:

#include <vector>
#include <algorithm>
#include <string>
#include <climits>
#include <stack>
#include <queue>
#include <map>
#include <cmath>
#include <iostream>
#include <unordered_map>
#include <cstring>
#include <iomanip>
#include <array>
#include <set>
#include <iterator>

using namespace std;
typedef long long ll;
using pll = pair<ll, ll>;
using pii = pair<int, int>;
#define F first;
#define S second;
ll mod = 1e9 + 7;
ll inf = 1e18;
const int MAX_N = 1e5 + 1;

typedef struct tri {
	ll a;
	ll b;
	ll c;
}tri;

ll gcd(ll x, ll y) {
	if (y > x) {
		ll z = y;
		y = x;
		x = z;
	}

	ll ans = y;
	while (x % y != 0) {
		ans = x % y;
		x = y;
		y = ans;
	}

	return ans;
}

ll binexp(ll n, ll p) {
	ll ans = 1;
	while (p) {
		if (p % 2) {
			ans = (ans * n) % mod;
		}
		n = (n * n) % mod;
		p /= 2;
	}
	return ans;
}

bool f(ll a, ll b) {
	return a > b;
}

void solve() {
	ll n; cin >> n;
	vector<ll>a(n), b(n);
	ll ans = 0, sum = 0;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
		ans += a[i] * a[i];
		sum += a[i];
	}
	for (int j = 0; j < n; j++) {
		cin >> b[j];
		ans += b[j] * b[j];
		sum += b[j];
	}

	ans *= (n - 2);

	vector<vector<ll>>dp(n, vector<ll>(1e4 + 1));
	dp[0][a[0]] = 1;
	dp[0][b[0]] = 1;
	for (int i = 1; i < n; i++) {
		for (int j = 0; j <= 1e4; j++) {
			if (j >= a[i]) dp[i][j] = dp[i][j] || dp[i - 1][j - a[i]];
			if (j >= b[i]) dp[i][j] = dp[i][j] || dp[i - 1][j - b[i]];
		}
	}

	ll mn = LLONG_MAX;
	for (int j = 0; j <= 1e4; j++) {
		if (!dp[n - 1][j]) continue;
		mn = min(mn, j * j + (sum - j) * (sum - j));
	}

	cout << ans + mn << endl;
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	int t; cin >> t;
	while (t--) {
		solve();
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

1702B - Polycarp Writes a String from Memory
1701A - Grass Field
489C - Given Length and Sum of Digits
886B - Vlad and Cafes
915A - Garden
356A - Knight Tournament
1330A - Dreamoon and Ranking Collection
1692B - All Distinct
1156C - Match Points
1675A - Food for Animals
1328C - Ternary XOR
1689A - Lex String
1708B - Difference of GCDs
863A - Quasi-palindrome
1478A - Nezzar and Colorful Balls
1581B - Diameter of Graph
404A - Valera and X
908A - New Year and Counting Cards
146A - Lucky Ticket
1594C - Make Them Equal
1676A - Lucky
1700B - Palindromic Numbers
702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array