Question details:
Rashof is the mayor of EMLand. EMLand consists of intersections and streets. There is exactly one path from each intersection to any of the other intersections. Intersections are denoted by positive intergers 1...n.
A construction company has offered Rashof to rebuild all streets of the EMLand, but Rashof can choose at most k of them to be rebuilt. The Construction company has offered a new length for each street which means after the street is rebuilt the length of the street changes.
Now Rashof as the mayor of the city must choose wisely so as to minimize sum of lengths of paths between all pairs of intersections.
Help Rashof!
Algorithm:
Notations: old edge length is L , new length is L' and set of edges E .
Count(C) number of edges(E') whose length is going to decrease i.e. L' < L
If C is less than or equal to K then
take all edges(E') into account i.e. Update length of all such edges in E
Else
1 . Sort all edges(E') based on (L'- L) in ascending order
2 . Sort those edges(E'' ⊆ E') whose (L'-L) is same based on L' in descending order
3.hoose 1st K edges(E''' ⊆ E') and update length of all such edges in E
Construct Graph G with Edge E and length L
Apply any shortest distance algorithm or DFS to find distance b/w each pair of node .
Implementation of above algorithm using priority queue and Dijkstra algorithm.
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
struct s{
int x;
int y;
int a;
int b;
int c;
};
const int MAX = 100000;
const long long INF = 100000000000000000;
vector< pii > G[MAX];
long long d[MAX];
void dijkstra(long long start) {
int u, v, i, c, w;
priority_queue< pii, vector< pii >, greater< pii > > Q;
for(i=0;i<MAX;i++){
d[i]=INF;
}
Q.push(pii(0, start));
d[start] = 0;
while(!Q.empty()) {
u = Q.top().second; // node
c = Q.top().first; // node cost so far
Q.pop(); // remove the top item.
if(d[u] < c) continue;
for(i = 0; i < G[u].size(); i++) {
v = G[u][i].first; // node
w = G[u][i].second; // edge weight
if(d[v] > d[u] + w) {
d[v] = d[u] + w;
//cout<<d[v];
Q.push(pii(d[v], v));
}
}
}
}
bool func(const s s1,const s s2) { return (s1.c < s2.c); }
bool func2(const s s1,const s s2) { return (s1.b < s2.b); }
int main() {
long long n, e, u, V, w,x,y,a,b,t,i,j,k,res,z=2;
s S;
vector<s> v;
map<pair<int,int>,int> m;
map<pair<int,int>,int>::iterator it;
cin>>t;
while(t--){
cin>>n>>k;
for(i = 1; i <= n; i++) G[i].clear();
v.clear();
m.clear();
for(i=1;i<n;i++){
cin>>x>>y>>a>>b;
if(b<a){
S.x = x;
S.y =y;
S.a=a;
S.b=b;
S.c=b-a;
v.push_back(S);
}
m[make_pair(x,y)]=a;
}
if(v.size()<=k){
for(i=0;i<v.size();i++){
m[make_pair(v[i].x,v[i].y)]=v[i].b;
}
it = m.begin();
for(;it!=m.end();++it){
u = it->first.first;
V = it->first.second;
w = it->second;
G[u].push_back(pii(V, w));
G[V].push_back(pii(u, w));
}
res = 0;
for(i=1;i<=n;i++){
dijkstra(i);
for(j= 1; j <= n; j++) {
if(i == j) continue;
if(d[j] >= INF) ;
else res+=d[j];
}
}
cout<<res/z<<"\n";
}
else{
sort(v.begin(),v.end(),func);
for(i=0;i<v.size();i++){
j = i;
while(v[i].c==v[j].c&&j<v.size())j++;
sort(v.begin()+i,v.begin()+j,func2);
i=j;
}
for(i=0;i<k;i++){
m[make_pair(v[i].x,v[i].y)]=v[i].b;
}
it = m.begin();
for(;it!=m.end();++it){
u = it->first.first;
V = it->first.second;
w = it->second;
G[u].push_back(pii(V, w));
G[V].push_back(pii(u, w));
}
res = 0;
for(i=1;i<=n;i++){
dijkstra(i);
for(j= 1; j <= n; j++) {
if(i == j) continue;
if(d[j] >= INF) ;
else res+=d[j];
}
}
cout<<res/z<<"\n";
}
}
return 0;
}
It passes only 2 test cases out of 9 test cases . Why this algorithm didn't work ?
or What are the modification should be done in this algorithm to get accepted ?
Reference:
Rashof, Mayor of EMLand
Traverse the tree/graph (eg nonrecursive DFS starting from any node) and count the number of times each edge is used (number of nodes on one side * number of nodes on the other side)
For each possible rebuild multiply delta by count
Sort
Profit
Notice that this is a tree, so, each edge connects two connected components.
Assume that we have edge connect between two connected components A and B, which contains n and m numbers of intersections, so, by decreasing the edge by x unit, we will decrease the total distance by n*m*x.
A---B---C----E
| |
| |
D---- -----F
Look at the graph above, edge between B and C connect two connected components, (A,B,D) and (C,E,F), decreasing the weight of this edge will decrease the distance between (A,B,D) and (C,E,F)
So, the algorithm is to select k edges, which has the largest n*m*x (if x is positive).
Related
So there is a list of points (x1,y1,z1),(x2,y2,z2),...(xn,yn,zn).
You can perform an operation O on any number of these points.
Operation O results in (x,y,z)= (max(x1,x2,...xn),max(y1,y2,...yn),max(z1,z2,...zn)).
Given (x,y,z), you need to determine whether it is possible to perform operation O on some of the points in the list to get (x,y,z) as a result.
For eg: You are given points(1,2,1),(3,1,4),(5,2,1).
Can you perform O operation to get 1) (3,2,1) 2) (1,1,1)
First line contains n and q i.e the number of points and no. of queries
Next n lines contain the n points space seperated
Next q lines contain the q points which are the queries
1<=q<=10^5
1<=n<=10^5
x,y,z are integers
Input:
2 2
1 3 5
5 3 1
5 3 5
3 3 3
Expected Output:
YES
NO
My logic:
for (int i = 0; i < q; i++)
{
cin>>x>>y>>z;
for (int j = 0; j < n; j++)
{
if(arr[j][0]==x && arr[j][1]<=y && arr[j][2]<=z)
first=1;
if(arr[j][0]<=x && arr[j][1]==y && arr[j][2]<=z)
second=1;
if(arr[j][0]<=x && arr[j][1]<=y && arr[j][2]==z)
third=1;
if(first+second+third==3)
break;
}
if(first+second+third==3)
cout<<"YES\n";
else
{
cout<<"NO\n";
}
first=0;
second=0;
third=0;
}
Note: Here arr[][] contains the given coordinates.
for every x y z in queries q I am performing this operation.
Few test cases are failing giving me a runtime error (Time limit Exceeded). Is there a better way to do this.
Your solution is correct but slow, has O(q * n) complexity which is 10^10 at maximum, too much.
I've solved your task using sorting plus merging search, which has O(n log n + q log q) complexity.
The algorithm is as follows:
For each of three cases, (x, y, z), (y, x, z), (z, x, y), signified as coordinates (i0, i1, i2), we do next:
Sort all points and queries by tuple (i0, i1, i2).
Among each equal coordinates i0 compute cumulative minimum of i2.
Merge sorted points and queries next way: For each range of queries and points with equal i0 and i1 take rightmost minimal i2. If such minimal i2 for point is greater than query's i2 then answer for this query is NO, otherwise is probably YES (probably meaning that it should be YES for all 3 orderings of (x, y, z)/(y, x, z)/(z, x, y)).
Basically algorithm above does same thing as your algorithm does, it finds point with equal x, y, or z so that other two coordinates are not greater. But does it through fast algorithm of merging two sorted arrays. So that merging itself takes just O(q + n) time, while whole algorithm time is dominated by sorting algorithms taking O(q log q + n log n) time.
Try it online!
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
using namespace std;
typedef int CoordT;
typedef tuple<CoordT, CoordT, CoordT> CoordsT;
typedef vector<CoordsT> CoordsVecT;
template <size_t i0, size_t i1, size_t i2>
static void Solve(CoordsVecT const & ps, CoordsVecT const & qs, vector<bool> & yes) {
auto Prep = [&](auto & s, auto const & o){
s.clear();
s.reserve(o.size());
for (size_t i = 0; i < o.size(); ++i)
s.push_back(make_tuple(get<0>(o[i]), get<1>(o[i]), get<2>(o[i]), i));
sort(s.begin(), s.end(), [](auto const & l, auto const & r) -> bool {
return get<i0>(l) < get<i0>(r) || get<i0>(l) == get<i0>(r) && (
get<i1>(l) < get<i1>(r) || get<i1>(l) == get<i1>(r) &&
get<i2>(l) < get<i2>(r)
);
});
};
vector< tuple<CoordT, CoordT, CoordT, size_t> > sps, sqs;
Prep(sps, ps);
Prep(sqs, qs);
vector<CoordT> mins2(sps.size());
CoordT cmin2 = 0;
for (size_t i = 0; i < sps.size(); ++i) {
if (i == 0 || get<i0>(sps[i - 1]) != get<i0>(sps[i]))
cmin2 = get<i2>(sps[i]);
cmin2 = std::min(cmin2, get<i2>(sps[i]));
mins2[i] = cmin2;
}
for (size_t iq = 0, ip = 0; iq < sqs.size(); ++iq) {
auto & cyes = yes[get<3>(sqs[iq])];
if (!cyes)
continue;
while (ip < sps.size() && get<0>(sps[ip]) < get<0>(sqs[iq]))
++ip;
if (ip >= sps.size() || get<0>(sps[ip]) != get<0>(sqs[iq])) {
cyes = false;
continue;
}
while (ip + 1 < sps.size() && get<0>(sps[ip + 1]) == get<0>(sqs[iq]) && get<1>(sps[ip + 1]) <= get<1>(sqs[iq]))
++ip;
if (ip >= sps.size() || get<1>(sps[ip]) > get<1>(sqs[iq]) || mins2[ip] > get<2>(sqs[iq])) {
cyes = false;
continue;
}
}
}
int main() {
size_t n = 0, q = 0;
cin >> n >> q;
auto Input = [](CoordsVecT & v, size_t cnt) {
v.reserve(v.size() + cnt);
for (size_t i = 0; i < cnt; ++i) {
CoordT x, y, z;
cin >> x >> y >> z;
v.push_back(make_tuple(x, y, z));
}
};
CoordsVecT ps, qs;
Input(ps, n);
Input(qs, q);
vector<bool> yes(qs.size(), true);
Solve<0, 1, 2>(ps, qs, yes);
Solve<1, 0, 2>(ps, qs, yes);
Solve<2, 0, 1>(ps, qs, yes);
for (size_t i = 0; i < qs.size(); ++i)
cout << (yes[i] ? "YES" : "NO") << endl;
return 0;
}
Input:
2 2
1 3 5
5 3 1
5 3 5
3 3 3
Output:
YES
NO
Background:
The problem is from leetcode:
In an N by N square grid, each cell is either empty (0) or blocked
(1).
A clear path from top-left to bottom-right has length k if and
only if it is composed of cells C_1, C_2, ..., C_k such that:
Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)
C_1 is at location (0, 0) (ie. has value grid[0][0])
C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])
If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).
Return the length of the shortest such clear path from top-left to
bottom-right. If such a path does not exist, return -1.
Question:
I was quite certain that my algorithm was correct but for this test case:
[[0,1,0,0,0],[0,1,0,0,0],[0,0,0,0,1],[0,1,1,1,0],[0,1,0,0,0]]
I get 9, and the correct answer is 7. Is there something I am doing wrong in the code below?
Code:
class Solution {
public:
std::vector<std::vector<int>> dirs = {{0,1},{1,0},{-1,0},{0,-1},{1,1},{-1,-1},{1,-1},{-1,1}};
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
if(grid.empty())
return 0;
if(grid[0][0] == 1 || grid[grid.size()-1][grid.size()-1] == 1)
return -1;
int m = grid.size(), n = grid[0].size();
std::pair<int, int> start = {0,0};
std::pair<int, int> end = {m-1, n-1};
std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false));
std::priority_queue<std::pair<int,int>> q;
q.push(start);
visited[start.first][start.second] = true;
int count = 1;
while(!q.empty())
{
auto cur = q.top();
q.pop();
if(cur.first == end.first && cur.second == end.second)
return count;
for(auto dir : dirs)
{
int x = cur.first, y = cur.second;
if(isValid(grid, x + dir[0], y + dir[1]))
x += dir[0], y += dir[1];
if(!visited[x][y])
{
visited[x][y] = true;
q.push({x,y});
}
}
count++;
}
return -1;
}
bool isValid(std::vector<std::vector<int>>& grid, int i, int j)
{
if(i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size() || grid[i][j] != 0)
return false;
return true;
}
};
This is not a problem for which you would use Dijkstra's algorithm. That algorithm is targetting weighted graphs, while the problem you are dealing with is unweighted. Moreover, the way you use a priority queue is wrong. A C++ priority queue will by default pop the element that is largest, but since you provide it coordinates, that means it will pop the element with the largest coordinates. This is obviously not what you need. In fact, you do not have anything to order nodes by, since this problem is about an unweighted graph.
Secondly, count is counting the total number of nodes you visit. That cannot be right, since you surely also visit nodes that are not on the shortest path that you eventually find.
This kind of problem is solved with a standard depth-first search. You can do it with two vectors (no need for stack, queue or deque, ...): the second vector gets populated with the unvisited neighbors of all the nodes in the first. Once that cycle is completed, you replace the first vector with the second, create a new second vector, and repeat... until you find the target node. The number of times you do this (outer) repetition corresponds to the length of the path.
Here is your shortestPathBinaryMatrix function with the necessary adaptations to make it work:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
if(grid.empty())
return 0;
if(grid[0][0] == 1 || grid[grid.size()-1][grid.size()-1] == 1)
return -1;
int m = grid.size(), n = grid[0].size();
pair<int, int> start = {0,0};
pair<int, int> end = {m-1, n-1};
vector<vector<bool>> visited(m, vector<bool>(n, false));
// no priority queue needed: the graph is not weighted
vector<std::pair<int,int>> q;
q.push_back(start);
visited[start.first][start.second] = true;
int count = 1;
while(!q.empty())
{
// just iterate the vector and populate a new one
vector<std::pair<int,int>> q2;
for(auto const& cur: q) {
if(cur.first == end.first && cur.second == end.second)
return count;
for(auto dir : dirs)
{
int x = cur.first, y = cur.second;
if(isValid(grid, x + dir[0], y + dir[1]))
x += dir[0], y += dir[1];
if(!visited[x][y])
{
visited[x][y] = true;
q2.push_back({x,y});
}
}
}
count++;
q = q2; // prepare for next iteration
}
return -1;
}
I have this problem from hackerearth
Given an array of N integers, C cards and S sum. Each card can be used
either to increment or decrement an integer in the given array by 1.
Find if there is any subset (after/before using any no.of cards) with
sum S in the given array.
Input Format
First line of input contains an integer T which denotes the no. of
testcases. Each test case has 2 lines of input. First line of each
test case has three integers N(size of the array), S(subset sum) and
C(no. of cards). Second line of each test case has N integers of the
array(a1 to aN) seperated by a space.
Constraints
1<=T<=100 1<=N<=100 1<=S<=10000 0<=C<=100 1<=ai<=100
Output Format
Print TRUE if there exists a subset with given sum else print FALSE.
So this is basically a variation of the subset sum problem, but instead of finding out whether a given subset with a sum S exists, we need to find the largest subset from sequence index to N-1 that has a value of s and compare it's length with our C value to see if it is greater. If it is, then we have enough elements to modify the sum using our C cards, and then we print out our answer. Here is my code for that
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N, S, C;
int checkSum(int index, int s, vector<int>& a, vector< vector<int> >& dP) {
if (dP[index][s] != -1)
return dP[index][s];
int maxNums = 0; // size of maximum subset array
for (int i = index; i < N; i++) {
int newSum = s - a[i];
int l = 0;
if (newSum == 0) {
l = 1;
} if (newSum > 0) {
if (i < (N-1)) { // only if we can still fill up sum
l = checkSum(i + 1, newSum, a, dP);
if (l > 0) // if it is possible to create this sum
l++; // include l in it
} else {
// l stays at 0 for there is no subset that can create this sum
}
} else {
// there is no way to create this sum, including this number, so skip it;
if (i == (N-1))
break; // don't go to the next level
// and l stays at 0
}
if (l > maxNums) {
maxNums = l;
}
}
dP[index][s] = maxNums;
return maxNums;
}
int main() {
int t;
cin >> t;
while (t--) {
cin >> N >> S >> C;
vector<int> a(N);
for (int i = 0; i < N; i++)
cin >> a[i];
vector< vector<int> > dP(N, vector<int>(S + C + 2, -1));
bool possible = false;
for (int i = 0; i <= C; i++) {
int l = checkSum(0, S-i, a, dP);
int m = checkSum(0, S+i, a, dP);
if ( (l > 0 && l >= i) || (m > 0 && m >= i) ) {
cout << "TRUE" << endl;
possible = true;
break;
}
}
if (!possible)
cout << "FALSE" << endl;
}
return 0;
}
So basically, 0 means it's not possible to create a subset equal to s from elements index to N-1, and -1 means we haven't computed it yet. And any other value indicates the size of the largest subset that sums up to s. This code isn't passing all the test cases. What's wrong?
You miss an else in following line
} if (newSum > 0) {
This make your program has an unexpected early break before updating maxNums by l in some cases.
For example, N=1, S=5, C=0, a={5}
Potential logic problem
You have limited the no. of card to be used to not exceed the subset size while the question never state you cannot apply multiple cards to same integers.
I mean l >= i and m >= i in
if ( (l > 0 && l >= i) || (m > 0 && m >= i) ) {
Seems you have logic flaw.
You need to find the shortest subset (with sum in range S-C..S+C) and compare it's size with C. If subset is shorter, it is possible to make needed sum.
Not allowed to modify the array ( The array is read only ).
Using constant extra space is allowed.
ex:
A : [2 1 4 3 2]
k : 3
answer : 2
I did it below way. The answer is correct but need to be more memory efficient.
void insert_sorted(vector<int> &B, int a,int k)
{
for(int i=0;i<k;i++)
{
if(B[i]>=a)
{
for(int j=k-1;j>i;j--)
B[j]=B[j-1];
B[i]=a;
return;
}
}
}
int Solution::kthsmallest(const vector<int> &A, int k) {
vector <int> B;
for(int i=0;i<k;i++)
{
B.push_back(INT_MAX);
}
int l=A.size();
for(int i=0;i<l;i++)
{
if(B[k-1]>=A[i])
insert_sorted(B,A[i],k);
}
return B[k-1];
}
One possible solution is binary search.
Let A be the input array; we want to find a number b such that exactly k items in A are smaller than b.
Obviously, b must be inside the range [0, max(A)].
And we do binary search starting with this range.
Suppose we are searching within range [lo, hi].
Let c = (lo + hi)/2 which is the middle pivot.
There are three cases:
number of items in A less than c are less than k.
In this case the number we search for should be larger than c, so it should be in range (c, hi]
number of items in A less than c are larger than k.
Similarly, the number we search for is in range [lo, c)
number of items in A less than c equals to k.
In this case, the answer is the minimum element in A that is greater than or equals to c. This can be find by doing a linear search in A again
The complexity is O(n log m), where m is the max element in A.
/* assume k is 0 based, i.e. 0 <= k < n */
int kth_element(const vector<int> &A, int k){
int lo = 0, hi = *max_element(A.begin(), A.end());
while (lo <= hi){
int mid = (lo + hi) / 2;
int rank_lo = count_if(A.begin(), A.end(), [=](int i){ return i < mid;});
int rank_hi = count_if(A.begin(), A.end(), [=](int i){ return i <= mid;});
if (rank_lo <= k && k < rank_hi)
return mid;
if (k >= rank_hi)
lo = mid + 1;
else
hi = mid - 1;
}
}
Although it's not the answer to this particular problem (as it requires a modifiable collection), there is a function called std::nth_element, which rearranges the elements so that the kth element is at position k, and all elements at positions less than k are smaller than or equal to the kth element, where k is a input parameter.
The question does not ask for any time constraints. An O(nk) solution is fairly simple, by iterating the array k times (at most), and discarding one element (and its duplicates) each time.
int FindKthSmallesr(const std::vector<int>& v, int k) {
// assuming INT_MIN cannot be a value. Could be relaxed by an extra iteration.
int last_min = INT_MIN;
while (k > 0) {
int current_min = INT_MAX;
for (int x : v) {
if (x <= last_min) continue;
current_min = std::min(current_min, x);
}
last_min = current_min;
for (int x : v) {
if (x == current_min) k--;
}
}
return last_min;
}
Code on ideone: http://ideone.com/RjRIkM
If only constant extra space is allowed, we can use a simple O(n*k) algorithm.
int kth_smallest(const vector<int>& v, int k) {
int curmin = -1;
int order = -1;
while (order < k) { // while kth element wasn't reached
curmin = *min_element(v.begin(), v.end(), [curmin](int a, int b) {
if (a <= curmin) return false;
if (b <= curmin) return true;
return a < b;
}); // find minimal number among not counted yet
order += count(v.begin(), v.end(), curmin); // count all 'minimal' numbers
}
return curmin;
}
online version to play with: http://ideone.com/KNMYxA
I was recently working on the following problem.
http://www.codechef.com/problems/D2
The Chef is planning a buffet for the DirectiPlex inauguration party, and everyone is invited. On their way in, each guest picks up a sheet of paper containing a random number (this number may be repeated). The guests then sit down on a round table with their friends.
The Chef now decides that he would like to play a game. He asks you to pick a random person from your table and have them read their number out loud. Then, moving clockwise around the table, each person will read out their number. The goal is to find that set of numbers which forms an increasing subsequence. All people owning these numbers will be eligible for a lucky draw! One of the software developers is very excited about this prospect, and wants to maximize the number of people who are eligible for the lucky draw. So, he decides to write a program that decides who should read their number first so as to maximize the number of people that are eligible for the lucky draw. Can you beat him to it?
Input
The first line contains t, the number of test cases (about 15). Then t test cases follow. Each test case consists of two lines:
The first line contains a number N, the number of guests invited to the party.
The second line contains N numbers a1, a2, ..., an separated by spaces, which are the numbers written on the sheets of paper in clockwise order.
Output
For each test case, print a line containing a single number which is the maximum number of guests that can be eligible for participating the the lucky draw.
Constraints
1 ≤ N ≤ 10000
You may assume that each number number on the sheet of paper; ai is randomly generated, i.e. can be with equal probability any number from an interval [0,U], where U is some upper bound (1 ≤ U ≤ 106).
Example
Input:
3
2
0 0
3
3 2 1
6
4 8 6 1 5 2
Output:
1
2
4
On checking the solutions I found this code:
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
#define LIMIT 37
using namespace std;
struct node {
int val;
int index;
};
int N;
int binary(int number, vector<int>& ans) {
int start = 0;
int n = ans.size();
int end = n - 1;
int mid;
if (start == end)
return 0;
while (start != end) {
mid = (start + end) / 2;
if (ans[mid] == number)
break;
if (ans[mid] > number)
end = mid;
else
start = mid + 1;
}
mid = (start + end) / 2;
return mid;
}
void display(vector<int>& list) {
cout << endl;
for (int i = 0; i < list.size(); i++)
cout << list[i] << " ";
cout << endl;
}
int maxsubsequence(vector<int>& list) {
vector<int> ans;
int N = list.size();
ans.push_back(list[0]);
int i;
// display(list);
for (i = 1; i < N; i++) {
int index = binary(list[i], ans);
/*if(index+1<ans.size())
continue;*/
if (list[i] < ans[index])
ans[index] = list[i];
if (list[i] > ans[index])
ans.push_back(list[i]);
// display(ans);
}
return ans.size();
}
int compute(int index, int* g) {
vector<int> list;
list.push_back(g[index]);
int itr = (index + 1) % N;
while (itr != index) {
list.push_back(g[itr]);
itr = (itr + 1) % N;
}
return maxsubsequence(list);
}
int solve(int* g, vector<node> list) {
int i;
int ret = 1;
for (i = 0; i < min(LIMIT, (int)list.size()); i++) {
// cout<<list[i].index<<endl;
ret = max(ret, compute(list[i].index, g));
}
return ret;
}
bool cmp(const node& o1, const node& o2)
{ return (o1.val < o2.val); }
int g[10001];
int main() {
int t;
cin >> t;
while (t--) {
cin >> N;
vector<node> list;
int i;
for (i = 0; i < N; i++) {
node temp;
cin >> g[i];
temp.val = g[i];
temp.index = i;
list.push_back(temp);
}
sort(list.begin(), list.end(), cmp);
cout << solve(g, list) << endl;
}
return 0;
}
Can someone explain this to me. I am well aware of calculating LIS in nlog(n).
What I am not able to understand is this part:
int ret = 1;
for (i = 0; i < min(LIMIT, (int)list.size()); i++) {
// cout<<list[i].index<<endl;
ret = max(ret, compute(list[i].index, g));
}
and the reason behind sorting
sort(list.begin(),list.end(),cmp);
This algorithm is simply guessing at the starting point and computing the LIS for each of these guesses.
The first value in a LIS is likely to be a small number, so this algorithm simply tries the LIMIT smallest values as potential starting points.
The sort function is used to identify the smallest values.
The for loop is used to check each starting point in turn.
WARNING
Note that this algorithm may fail for certain inputs. For example, consider the sequence
0,1,2,..,49,9900,9901,...,99999,50,51,52,...,9899
The algorithm will try just the first 37 starting points and miss the best starting point at 50.
You can test this by changing the code to:
int main() {
int t;
t=1;
while (t--) {
N=10000;
vector<node> list;
int i;
for (i = 0; i < N; i++) {
node temp;
if (i<50)
g[i]=i;
else if (i<150)
g[i]=9999-150+i;
else
g[i]=i-100;
temp.val = g[i];
temp.index = i;
list.push_back(temp);
}
sort(list.begin(), list.end(), cmp);
cout << solve(g, list) << endl;
}
return 0;
}
This will generate different answers depending on whether LIMIT is 37 or 370.
In practice, for randomly generated sequences it will have a good chance of working (although I don't know how to compute the probability exactly).