博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
从一列数中筛除尽可能少的数,使得从左往右看这些数是从小到大再从大到小...
阅读量:4131 次
发布时间:2019-05-25

本文共 2060 字,大约阅读时间需要 6 分钟。

问题:从一列数中筛除尽可能少的数使得从左往右看,这些数是从小到大再从大到小的(网易)。

解法:这是双端 LIS 问题,用 DP 的思想可解,目标规划函数 max{ b[i] + c[i] }, 其中 b[i] 为从左到右, 0 ~ i 个数之间满足递增的数字个数; c[i] 为从右到左, n-1 ~ i 个数之间满足递增的数字个数。最后结果为 n - max + 1。其中 DP 的时候,可以维护一个 inc[] 数组表示递增数字序列,inc[i] 为从小到大第 i 大的数字,然后在计算 b[i] c[i] 的时候使用二分查找在 inc[] 中找出区间 inc[0] ~ inc[i-1] 中小于 a[i] 的元素个数(low)。

源代码如下:

/** * The problem: * 从一列数中筛除尽可能少的数使得从左往右看,这些数是从小到大再从大到小的(网易)。 * use binary search, perhaps you should compile it with -std=c99 * fairywell 2011 */  #include 
#define MAX_NUM (1U<<31) int main() { int i, n, low, high, mid, max; printf("Input how many numbers there are: "); scanf("%d/n", &n); /* a[] holds the numbers, b[i] holds the number of increasing numbers * from a[0] to a[i], c[i] holds the number of increasing numbers * from a[n-1] to a[i] * inc[] holds the increasing numbers * VLA needs c99 features, compile with -stc=c99 */ double a[n], b[n], c[n], inc[n]; printf("Please input the numbers:/n"); for (i = 0; i < n; ++i) scanf("%lf", &a[i]); // update array b from left to right for (i = 0; i < n; ++i) inc[i] = (unsigned) MAX_NUM; //b[0] = 0; for (i = 0; i < n; ++i) { low = 0; high = i; while (low < high) { mid = low + (high-low)*0.5; if (inc[mid] < a[i]) low = mid + 1; else high = mid; } b[i] = low + 1; inc[low] = a[i]; } // update array c from right to left for (i = 0; i < n; ++i) inc[i] = (unsigned) MAX_NUM; //c[0] = 0; for (i = n-1; i >= 0; --i) { low = 0; high = i; while (low < high) { mid = low + (high-low)*0.5; if (inc[mid] < a[i]) low = mid + 1; else high = mid; } c[i] = low + 1; inc[low] = a[i]; } max = 0; for (i = 0; i < n; ++i ) if (b[i]+c[i] > max) max = b[i] + c[i]; printf("%d number(s) should be erased at least./n", n+1-max); return 0; }

转载地址:http://innvi.baihongyu.com/

你可能感兴趣的文章
数据库
查看>>
nginx反代 499 502 bad gateway 和timeout
查看>>
linux虚拟机安装tar.gz版jdk步骤详解
查看>>
python实现100以内自然数之和,偶数之和
查看>>
python数字逆序输出及多个print输出在同一行
查看>>
苏宁产品经理面经
查看>>
百度产品经理群面
查看>>
去哪儿一面+平安科技二面+hr面+贝贝一面+二面产品面经
查看>>
element ui 弹窗在IE11中关闭时闪现问题修复
查看>>
vue 遍历对象并动态绑定在下拉列表中
查看>>
Vue动态生成el-checkbox点击无法选中的解决方法
查看>>
python __future__
查看>>
MySQL Tricks1
查看>>
python 变量作用域问题(经典坑)
查看>>
pytorch
查看>>
pytorch(三)
查看>>
ubuntu相关
查看>>
C++ 调用json
查看>>
nano中设置脚本开机自启动
查看>>
动态库调动态库
查看>>