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.
Input
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
Output a single integer — the answer to the problem.
题意:
给你n个数,要你构建一张图,节点有n个,逆序的节点分别建一条无向边。问最大独立子集是多少。
思路:
这题首先要明白独立子集是什么,然后分析可得只有递增的数(非严格)才能构成独立子集,最大独立子集即最长不下降子序列。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn=1e5+100;
int a[maxn];
int dp[maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=n;i++)
{
if(a[i]>=dp[dp[0]])
{
dp[++dp[0]]=a[i];
}
else
{
int pos=upper_bound(dp+1,dp+dp[0]+1,a[i])-dp;
dp[pos]=a[i];
}
}
printf("%d\n",dp[0]);
return 0;
}
总结:这是一道转换成经典模型的题目。

博客围绕图的最大独立子集问题展开。给定n个数构建图,逆序节点建无向边,求最大独立子集。分析得出只有递增数能构成独立子集,最大独立子集即最长不下降子序列,是一道可转换成经典模型的题目。
2107

被折叠的 条评论
为什么被折叠?



