【树状数组优化哈希DP】CF1801 C

Problem - C - Codeforces

【树状数组优化哈希DP】CF1801 C_第1张图片

思路:

【树状数组优化哈希DP】CF1801 C_第2张图片 

Code:

#include 
 
#define lowbit(x) (x & (-x))

using i64 = long long;
 
constexpr int N = 2e5 + 10;
constexpr int mod = 1e9 + 7;

std::vector V[N];

int n, m, x, mxv = 0;
int a[N], id[N], tr[N];

bool cmp(int x, int y) {
	return V[x][V[x].size() - 1] < V[y][V[y].size() - 1];
}
void add(int x, int k) {
	for (int i = x; i <= mxv; i += lowbit(i)) {
		tr[i] = std::max(tr[i], k);
	}
}
int sum(int x) {
	int res = 0;
	for (int i = x; i; i -= lowbit(i)) {
		res = std::max(res, tr[i]);
	}
	return res;
}
void solve() {
	std::cin >> n;

	mxv = 0;
	for (int i = 1; i <= n; i ++) {
		id[i] = i;
		V[i].clear();
		std::cin >> m;
		int mx = 0;
		for (int j = 1; j <= m; j ++) {
			std::cin >> x;
			if (mx < x) V[i].push_back(x);
			mx = std::max(mx, x);
		}
		mxv = std::max(mxv, mx);
	}

	std::sort(id + 1, id + 1 + n, cmp);

	for (int x = 1; x <= n; x ++) {
		int i = id[x];
		int mx = 0;
		for (int j = 0; j < V[i].size(); j ++) {
			mx = std::max(mx, sum(V[i][j] - 1) + (int)V[i].size() - j);
		}

		add(V[i][V[i].size() - 1], mx);
	}

	std::cout << sum(mxv) << "\n";

	for (int i = 1; i <= n; i ++) {
		for (int j = V[i].back(); j <= 2e5; j += lowbit(j)) {
			tr[j] = 0;
		}
	}
}
signed main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
 
    int t = 1;
	std::cin >> t;
    while(t --) {
        solve();
    }
    return 0;
}

 

你可能感兴趣的:(线段树与树状数组,动态规划,哈希算法,算法)