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
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
题目大意:
我们都学过冒泡排序,对于一个具有N个元素的序列来讲,每一次遍历数组,比较相邻两个数字的大小,如果a【i】>a【i+1】,将两个元素调换,直到最终排序成功为止。
现在如果存在了a【i】>a【i+1】.那么现在在一个具有N个点的图中建出无向边,连接a【i】和a【i+1】两个点。
问最大独立集的size是多大。
思路:
最大独立集:一个集合中所有点之间都没有连边。
我们通过枚举和思考可以得知:对于原序列来讲,若存在a【i】>a【j】的话(j>i),那么一定存在建边:Add(a【i】,a【j】).
那么反之,若存在a【i】<a【j】的话,那么两点之间一定没有建边。
那么我们能够递推出一个关系,如果a【i】和a【j】之间不能建边,而且a【j】和a【k】之间不能建边,那么a【i】和a【k】之间也一定不能建边。(i<j<k)
那么问题其实就是在求原序列的最长上升子序列的长度。
n范围比较大,采用二分思维nlogn去做即可。
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 444444
using namespace std;
int f[N];
int main()
{
int n;
while(~scanf("%d",&n))
{
int c=0;
for(int i=1;i<=n;i++)
{
int t;
scanf("%d",&t);
if(i==1) f[++c]=t;
else
{
if(t>f[c]) f[++c]=t;//最长非递减就变成等号即可。
else
{
int pos=lower_bound(f+1,f+c,t)-f;//二分找到数组中比t大的第一个元素的的地址。
f[pos]=t;
}
}
}
printf("%d\n",c);
}
}