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

来源:互联网 发布:折装导轮的工具的数据 编辑:程序博客网 时间:2024/05/18 20:51

题目: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;}// LISint L = 0;for (int i = 0; i < n; i++) {// binary searchint 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 1M[newL] = i;L = newL;} else {if (x[M[newL]] >= x[i]) {M[newL] = i;}}}return L;}};/************** Program End ************************/


0 0