Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output a single integer — the answer to the problem.
3
3 1 2
2
思路:用len[i]记录长度为i时的上升子序列对应的最小的那个数,每次插入一个数就更新len数组,使用二分查找进行修改操作,时间复杂度为O(nlogn),最后i的值就是上升子序列的最大长度。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 int a[100005]; 6 int Binary(int temp, int len) 7 { 8 int l = 1, r = len, mid; 9 while(l <= r) 10 { 11 mid = (l + r) >> 1; 12 if(temp > a[mid]) 13 l = mid + 1; 14 else 15 r = mid - 1; 16 } 17 return l; 18 } 19 20 int main(int argc, char const *argv[]) 21 { 22 int n, len, k, temp, idx; 23 /* freopen("in.c", "r", stdin); */ 24 while(~scanf("%d", &n)) 25 { 26 len = 0; 27 memset(a, 0, sizeof(a)); 28 for(int i = 1;i <= n;i ++) 29 { 30 scanf("%d", &temp); 31 if(temp > a[len]) 32 a[++len] = temp; 33 else 34 { 35 idx = Binary(temp, len); 36 a[idx] = temp; 37 } 38 } 39 printf("%d ", len); 40 } 41 return 0; 42 }