Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save henrybear327/a3c98628bbea8cba3b82510dadb57584 to your computer and use it in GitHub Desktop.
Save henrybear327/a3c98628bbea8cba3b82510dadb57584 to your computer and use it in GitHub Desktop.
weighted longest increasing subsequence
// max weight, might not be the LIS!
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
scanf("%d", &n);
map<int, int> dp;
int v[n], w[n];
for (int i = 0; i < n; i++)
scanf("%d", &v[i]);
for (int i = 0; i < n; i++)
scanf("%d", &w[i]);
for (int i = 0; i < n; i++) {
if (dp.count(v[i]) == 0) {
auto loc = dp.upper_bound(v[i]);
int add = w[i];
if (loc != dp.begin()) {
loc--;
add += loc->second;
}
dp[v[i]] = add;
} else {
auto loc = dp.find(v[i]);
if (loc != dp.begin()) {
loc--;
dp[v[i]] = max(dp[v[i]], loc->second + w[i]);
} else {
dp[v[i]] = max(dp[v[i]], w[i]);
}
}
auto loc = dp.find(v[i]);
int val = dp[v[i]];
loc++;
while (loc != dp.end() && val >= loc->second) {
loc = dp.erase(loc);
}
}
// for (auto i : dp)
// printf("%d %d\n", i.first, i.second);
printf("%d\n", dp.rbegin()->second);
}
int main()
{
int ncase;
scanf("%d", &ncase);
while (ncase--)
solve();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment