SRM 626 D1L2:CatchTheBeat,Longest increasing subsequence,O(NlogN) 算法

题目:http://community.topcoder.com/stat?c=problem_statement&pm=12807&rd=15856

参考:http://apps.topcoder.com/wiki/display/tc/SRM+623

开始用dp,时间复杂度为O(N^2),直接超时了。这道题目很难的一点就是将问题抽象成Longest_increasing_subsequence问题,详见参考

代码:

#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <sstream>
#include <iomanip>

#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;

#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)
typedef pair<int, int> pii;
typedef long long llong;
typedef pair<llong, llong> pll;
#define mkp make_pair

/*************** Program Begin **********************/
int M[500001];
vector <int> x, y;

class CatchTheBeat {
public:
	int maxCatched(int n, int x0, int y0, int a, int b, int c, int d, int mod1, int mod2, int offset) {
		x.resize(n); y.resize(n);
		x[0] = x0;
		for (int i = 1; i < n; i++) {
			x[i] = (x[i-1] * (long long)a + b) % mod1;
		}

		for (int i = 0; i < n; i++) {
			x[i] = x[i] - offset;
		}
		y[0] = y0;
		for (int i = 1; i < n; i++) {
			y[i] = (y[i-1] * (long long)c + d) % mod2;
		}
		vector <pii> v;
		for (int i = 0; i < n; i++) {
			if (abs(x[i]) > y[i]) {
				continue;
			}
			v.push_back(mkp(x[i] + y[i], y[i] - x[i]));
		}
		sort(v.begin(), v.end());
		n = v.size();
		memset(M, 0, sizeof(M));
		for (int i = 0; i < n; i++) {
			x[i] = v[i].second;
		}
		// LIS
		int L = 0;
		for (int i = 0; i < n; i++) {
			// binary search
			int lo = 1, hi = L;
			int mid;
			while (lo <= hi) {
				mid = (lo + hi) / 2;
				if (x[M[mid]] > x[i]) {
					hi = mid - 1;
				} else {
					lo = mid + 1;
				}
			}
			int newL = lo;
			if (newL > L) {		// sequence length increase 1
				M[newL] = i;
				L = newL;
			} else {
				if (x[M[newL]] >= x[i]) {
					M[newL] = i;
				}
			}
		}
	
		return L;
	}

};

/************** Program End ************************/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值