page

从头刷到了从欧拉公式到初等群论了,=。=做点基于个人知识的笔记。

如果有大佬会,求大佬解答。

音乐与测度论有什么关系?希尔伯特曲线:无限数学怎样应用于有限世界中不是很理解的是:既然有理数的测度为0,那么为什么通过曲线覆盖空间。不过一维到二维的映射让我首次认识到这类曲线的一种用途。Orz

octave-online

线代视屏收货蛮多的,主要在基变换的部分,但和ssj大佬用式子分析下来,虽然看上去是图像理解,可以说更多的还是让过程更复杂了。其中视频中没有讲在一起的有矩阵乘法的意义。以及我认为它把[0 -1 ; 1 0]称作旋转90°并不完全科学

例如[A]*[B]矩阵AB相乘

从右向左看,首先对原坐标系的基做B的变换,再做A的变换 其变换的视角是基于标准坐标系的,例如[0 -1 ; 1 0]*[1 1 ; 0 1]

先看[1 1 ; 0 1]是把 原来的基变为newx = oldx,newy=oldx+oldy,而左边的矩阵为视频中的逆时针转90°,这里都是基于 标准坐标系。

从左向右看 首先newx=oldy,newy=-oldx,然后[1 1 ; 0 1]需要将视角转过来以新的基的视角进行[1 1;0 1]的变换,如果按照原坐标系进行变换得到的是[1 -1; 1 0]

第一次从图像上看到特征值和特征向量,抽象向量空间也是感觉棒棒哒。

然后是群论没有看懂的是如何从加法群到乘法群就有了2^x的群,中间的乘法到幂的过度没理解。

总评

整理开始日期:2017-01-23

整理结束日期:2017-06-21

如果你是准备学习算法,那么我非常不建议看这本书,去系统性的多刷刷题吧。

本书适用人群:觉得无聊想了解一下算法有什么用的人,准备参加大公司面试,且技术方面已经准备好的人,学习累了想消遣一下的人。

第一章 游戏中碰到的题目

章节 标题 整理
1.1 关于cpu的/window的相关 主要用于装逼,和后面的题目毫无相似性
1.2 中国象棋将帅的问题 最基础的编解码+C的struct知识
1.3 一摞烙饼的排序,对一个数组每次取首部任意个进行翻转求最少次数 深搜枚举剪枝 扩展问题很棒
1.4 买书,n(<6)种物品每件物品价格相同,当同时买k种不同的物品各一件时将会有f(k)=((2,3,4,5)=>(5%,10%,20%,25%)的折扣)求最大折扣 动规
1.5 快速找出故障机器,找唯一的仅出现一次的数 位表示
1.6 饮料供货,每个饮料容量为2的幂, 记忆dp/基于数字特征的贪心
1.7 光影切割问题 。。。
1.8 小飞的电梯调度算法,一堆整数的整数差值最小 。。。
1.9 高效率地安排见面会 图着色问题
1.10 双线程高效下载
1.11 NIM(1)一排石头的游戏 维持和问题
1.12 NIM(2)“拈”游戏分析 反向递推博弈转化 XOR的转换和维持
1.13 NIM(3)两堆石头的游戏 反向递推博弈转化 质数筛法!
1.14 连连看游戏设计 。。
1.15 构造数独 生成再去除
1.16 24点游戏 注意分数。。
1.17 俄罗斯方块游戏 如何移动旋转 估分(洞 过高)
1.18 挖雷游戏 ???

第2章 数字之魅——数字中的技巧

章节 标题 整理
2.3 寻找发帖“水王” 求出现次数超过1/2的数
2.7 最大公约数问题 剔除了同偶数共除2和有偶数去2的优化
2.8 找符合条件的整数 寻找1、0组成的能整除的被除数 利用数值特性余数进行效率优化
2.20 程序理解和时间分析

第3章 结构之法——字符串及链表的探索

章节 标题 整理
3.6 编程判断两个链表是否相交 链表成环问题
3.11 程序改错

第4章 数学之趣——数学游戏的乐趣

章节 标题 整理
4.1 金刚坐飞机问题
4.3 买票找零 卡特兰数
4.4 点是否在三角形内 计算几何 向量叉乘
4.5 磁带文件存放优化 数学。。
4.6 桶中取黑白球 奇偶分析6666666 感觉可以加入洗脑密卷豪华套餐
4.7 蚂蚁爬杆 等效转化!
4.8 三角形测试用例 编码 测试用例应当足量
4.9 数独知多少 思路与估值
4.11 挖雷游戏的概率

突然无聊 学学emacs [该记录用vim编写]

交换

setxkbmap -option "ctrl:swapcaps"

1
2
显示行号
M-x linum-mode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
                 M-v
C-p
|
M-a C-a M-b C-b Cursor C-f M-f C-e M-e
|
C-n
C-v
取消 操作 C-g
退出 C-x C-c
剪切 删除 C-d
C-k
粘贴 C-y
撤销 C-x u
C-/
C-_

文件

1
2
3
4
5
6
7
8
9
10
11
12
打开 C-x C-f
保存 C-x C-s
C-x C-w : save file as

保存多个缓存区 C-x s

显示缓冲区 C-x C-b

切换缓存区 C-x b

关闭其它所有窗格 只保留一个
C-x 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
文字替换      M-x repl s<Return>src<Return>dst<Resturn>
恢复自动保存的 M-x recover

切换模式
M-x fundamental-mode (主模式)
M-x text-mode (文本模式)
M-x auto-fill-mode (自动 折 行 模式) C-u 20 C-x f 设置折叠字符数为20
M-q 手动折叠行

查看主模式的文档 C-h m

搜索 C-s
在搜索中再按C-s可以往后搜索 C-r 与之搜索方向相反

C-x 2 上下分割窗口
C-x 3 左右

C-M-v下别的移动 C-M-S-v上移动
切换到其它窗口 C-x o

打开文件 并跳过去
C-x 4 C-f 上下
`

显示行号
M-x linum-mode

1

             M-v
             C-p
              |

M-a C-a M-b C-b Cursor C-f M-f C-e M-e
|
C-n
C-v
取消 操作 C-g
退出 C-x C-c
剪切 删除 C-d
C-k
粘贴 C-y
撤销 C-x u
C-/
C-_

1
2
3
4

# 文件


打开 C-x C-f
保存 C-x C-s
C-x C-w : save file as

保存多个缓存区 C-x s

显示缓冲区 C-x C-b

切换缓存区 C-x b

关闭其它所有窗格 只保留一个
C-x 1

1
2
3

---

文字替换 M-x repl ssrcdst
恢复自动保存的 M-x recover

切换模式
M-x fundamental-mode (主模式)
M-x text-mode (文本模式)
M-x auto-fill-mode (自动 折 行 模式) C-u 20 C-x f 设置折叠字符数为20
M-q 手动折叠行

查看主模式的文档 C-h m

搜索 C-s
在搜索中再按C-s可以往后搜索 C-r 与之搜索方向相反

C-x 2 上下分割窗口
C-x 3 左右

C-M-v下别的移动 C-M-S-v上移动
切换到其它窗口 C-x o

打开文件 并跳过去
C-x 4 C-f 上下


=.= 已经基本放弃了 继续vim

该书版本2015.06

基于个人已有知识整理 低分享价值

章节

  1. java 是什么 java web是什么
  2. 各种java web容器 以及IDE的使用
  3. Servlet without jsp
  4. basic jsp syntax ,jsp 和servlet 在server端的互相forward
  5. cookie/session 以及相关安全知识
  6. jsp 表达式语句 $,#
  7. jsp 标签库 c fmt fn x sql
  8. jsp 自定义标签与函数库 .tag .tld
  9. 过滤器 (日志 验证 压缩加密 错误处理)
  10. WebSocket 进行交互 (ajax,adobe flash等 各类访问 的设计) 在线对战井字棋 集群
  11. 日志监控
  12. Spring

Source code

Here

相关

runnoob jsp

tomcat 个人理解

和php+apache类似

遇到请求是jsp则找jsp

如果是其它url则根据/WEB-INF/web.xml的servlet配置去找对应的class (这些都没有main函数 继承自HttpServlet)

配置web.xml也可以用java 的@WebServlet注解代替

依赖

sudo apt-get install default-jdk idea tomcat8

把个人用户添加到tomcat8的组里[???必要么]

servlet

文件上传 @MultipartConfig()

1
2
3
4
5
@MultipartConfig(
fileSizeThreshold = 5_242_880,//小于5MB保存在内存中
maxFileSize = 20_231L , //5~20MB保存在location(可设置 不设置则java默认)
maxRequestSize = 41_943_040L //拒绝>20MB文件 或 >40MB请求
)

通过request.getParameter(“action”)来判断 是要 请求 上传 下载 还是什么操作(下载需要注意设置返回头)

request.getPart(“file1”)来接受上传的文件

jsp

<%@ 指令 %> 例如说明文档 类型 引入依赖等
<% page %>
<% include %>
<% taglib %>
<%! 声明 %> 如声明定义变量 函数
<% 脚本 %> 赋值运算 貌似也可以在这里声明
<%= 表达式 %>运算
<%– 注释 –%>运算

表达式语句保留字 true false null instanceof empty div mod and or not eq ne lt gt le ge

表达式 的流处理 以及lambda

java 标准标签库规范的5个标签库 c 核心,fmt 格式化, fn 函数, sql, x XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="https://java.sun.com/jsp/jstl/fn" %>
<%@ taglib prefix="sql" uri="https://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="x" uri="https://java.sun.com/jsp/jstl/x" %>


<c:out value="${exp}" default="value is null">
<c:out value="${exp}">value is null</c:out>

<c:url value="http://....../today.jsp">
<c:param name="story" value="${storyId}">
<c:param name="seo" value="${seoString}">
</c:url>

<c:if test=>
balabala
</c:if>
c:choose c:when c:otherwise c:forEach c:forTokens c:redirect c:import c:set c:remove

fmt:message fmt:setLocale fmt:bundle fmt:setBundle fmt:requestEncoding fmt:timeZone fmt:setTimeZone fmt:formatDate fmt:parseDate fmt:formatNumber fmt:parseNumber
对应还有i18n的配置

(不推荐)sql:transaction sql:update sql:param sql:dateParam sql:query

(x 命名空间)

过滤器

继承Filter 重写函数doFilter init destroy,通过chain.doFilter向下传递

也可以在java内用代码配置 FilterGegistration

因为排序问题请勿使用注解来配置过滤器 (URL映射优先级 > Servlet映射)

filter-mapping可以用 不同方式配置 需要过滤的链接

1
2
3
4
5
6
7
8
9
<filter>
<filter-name>myf</filter-name>
<filter-class>com.wrox.fff</filter-class>
</filter>
<filter-mapping>
<filter-name>myf</filter-name>
<url-pattern>/foo</url-pattern>
<servlet-name>ticketServlet</servlet-name>
</filter-mapping>

压缩过滤器extends HttpServletResponnseWrapper

WebSocket

会使用443(wss)端口 以及Http/1.1中的 Connection:Upgrade

HTTP开始 然后用TCP连接的WebSocket交流

1
2
3
4
5
6
7
8
9
10
11
12
var connection = new WebSocket('ws://www.example.net/safsd');
var connection = new WebSocket('wss://secure.example.net/safsd');
var connection = new WebSocket('ws://www.example.net/safsd','asdf');
var connection = new WebSocket('ws://www.example.net/safsd',{'wer','qwef'});

if(connection.readyState == WebServlet.OPEN){qwer;}


connection.onopen = function(event){}
connection.onclose = function(event){}
connection.onerror = function(event){}
connection.onmessag = function(event){}

利用WebSocket可以实现 在线对战游戏 比如 井字棋

Server:

session来记录用户

@ServerEndpoint("/ticTacToe/{gameId}/{username}")

onOpen()

onMessage()

onClose()

发送消息

session.getBasicRemote().sendText(ttttteeeeexxxxxttttt)以及 close的另外的函数

前端js

上面的new WebSocket(*)on* + server.send


用WebSocket 做集群

@ClientEndpoint

ClusterMessage

做用户端的 extends HttpServlet

日志监控

maven -> org.apache.logging.log4j -> log4j-api/log4j-core/...

System.err.println/Sytem.out.println并不完美 因为它们永远启用 并在代码中

要记录的内容:错误/警告/错误类型/栈/JVM状态/一些需要审核的事的记录 比如医院

记录方法:普通的println/平面日志/XML/JSON/ linux的syslog/套接字/SMTP SMS/DB

分级:重要性 n MB/s的日志 = 无日志 ,例如java.util.logging.Level分类 (也有其它分类 如apache的不同级别)

  • 致命/崩溃 无常量
  • 错误 SEVERE
  • 警告 WARNING
  • 信息 INFO
  • 配置细节 CONFIG
  • 调试 FINE
  • 追踪1/2 FINER FINEST

通过 java.util.logging.LogManager解耦合,注意日志必要性和性能影响的权衡

框架 log4j,slf4j,logback,log4j2

log4j2的 记录器(),日志储存器,布局,过滤器

log4j2将寻找 log4j2log4j2-test支持的扩展类型有.xml,.json.jsn

Spring framework

其它

java编译后 单个实现不能超过65535个字节=.=……….

官方文档

总的图 来自实验楼https://www.shiyanlou.com/courses/109

实验楼

java.lang不需要import

String 内部不可变,StringBuffer 内部可变

看到下面这图我 哇的一声就哭了

设计模式之间关系

哇 心态崩了–google一堆资料能运行的没几个,以及上来就是一大堆代码,一点循序渐进的学习过程都没有,而且也没有不用和用的对比显示的区别

最后还是看了实验楼爸爸的spring教程,感谢!!感谢!!


我使用的环境

  • OS:4.9.0-deepin4-amd64 是Debian分 支下类似Ubuntu的
  • javac/java: javac 1.8.0_111 [apt-get install default-jdk]
  • maven : Apache Maven 3.3.9
  • idea : 2017.1

然后 学spring之需要有些的基础知识,个人认为是必备

代码层面的基础

  • JAVA SE/ core-java /就是基本的语法 类啊 继承啊 IO啊之类的东西
  • xml 这个看得很快的 就是个xml是个怎样的数据结构

要用的工具层面

  • maven [apt-get install maven] 看看5Min GuideGetting start 不需要太细 但要理解单独的maven是个啥
  • javac 大自感受了一下java的代码中的.和文件路径的/的关系
  • idea [apt-get install idea] 我用的IDE

知识层面


然后学习路径跟着实验楼爸爸的教程就好了 :-) 这里只做一些个人的笔记

idea相关

总的流程讲道理比eclipse简洁太多

Ctrl+Alt+Shift+SModules->Sources 代码根目录需要Mark as为Sources才能 右键添加Java类:-),resources文件夹也需要Mark as 成Resources

新建类 直接输入从起始到类名 如 com.abc.HelloWorld

运行左边的Edit Configurations->左上角加号->Application->设置Main class即可

新建xml中有spring选项简直完美

maven 相关

pom.xml中需要加上对spring的具体的某些库的依赖的配置 然后idea/maven会自动帮你下载:-)

spring 相关

一个bean 的 id 是一个随意的名字 它可以被java代码通过改名字得到

class是对应的Java代码的具体的类

name/value以键值对的形式 设置class类中的name对应的field

1
2
3
4
<bean id="FileNameGenerator" class="com.shiyanlou.spring.bean.FileNameGenerator">
<property name="name" value="shiyanlou"/>
<property name="type" value="txt"/>
</bean>

把bean设为另一个bean的使用ref

1
2
3
4
5
6
7
8
9
<bean id="CustomerBean" class="com.shiyanlou.spring.innerBean.Customer">
<property name="person" ref="PersonBean" />
</bean>

<bean id="PersonBean" class="com.shiyanlou.spring.innerBean.Person">
<property name="name" value="shiyanlou" />
<property name="address" value="chengdu" />
<property name="age" value="25" />
</bean>

用java代码得到bean

1
2
context = new ClassPathXmlApplicationContext("SpringBeans.xml");   //xml的文件名
Customer obj = (Customer) context.getBean("CustomerBean"); //上面的一个具体的id

bean的参数scope

  1. singleton — 单例模式,由 IOC 容器返回一个唯一的 bean 实例。
  2. prototype — 原型模式,被请求时,每次返回一个新的 bean 实例。
  3. request — 每个 HTTP Request 请求返回一个唯一的 Bean 实例。
  4. session — 每个 HTTP Session 返回一个唯一的 Bean 实例。
  5. globalSession — Http Session 全局 Bean 实例。

example:

<bean id="CustomerService" class="com.shiyanlou.spring.customer.services.CustomerService" scope="prototype"/>


bean 除了基本的int string也支持java的list map等 见实验楼爸爸的文档


代码中的spring @Component

1
2
3
4
5
6
packeage com.shiyanlou.spring;

@Component("shiyanlou")
public class shiyanlou{

}

与在XML中配置以下效果相同

1
<bean id="shiyanlou" class="com.shiyanlou.spring.shiyanlou">

还有@Autowired,@Configuration@Bean


自动扫描组件 减少 xml的繁琐配置

@Component +@Autowired+

1
<context:component-scan base-package="com.shiyanlou.spring" />

默认情况下,Spring 将把组件 Class 的第一个字母变成小写,来作为自动扫描组件的名称,例如将 CustomerService 转变为 customerService


增加代码阅读性

  1. @Component ——表示一个自动扫描 component
  2. @Repository ——表示持久化层的 DAO component
  3. @Service ——表示业务逻辑层的 Service component
  4. @Controller ——表示表示层的 Controller component

用filter+regex来include 省去@Component

1
2
3
4
<context:component-scan base-package="com.shiyanlou.spring" >
<context:include-filter type="regex" expression="com.shiyanlou.spring.dao.*DAO.*" />
<context:include-filter type="regex" expression="com.shiyanlou.spring.services.*Service.*" />
</context:component-scan>

自动装配Bean 属性autowire //自动装配如果找不到即为null

  1. no —— 默认情况下,不自动装配,通过 ref attribute手动设定。
  2. byName —— 根据 Property 的 Name 自动装配,如果一个 bean 的 name ,和另一个 bean 中的 Property 的 name 相同,则自动装配这个 bean 到 Property 中。
  3. byType —— 根据 Property 的数据类型( Type )自动装配,如果一个 bean 的数据类型,兼容另一个 bean 中 Property 的数据类型,则自动装配。
  4. constructor —— 根据构造函数参数的数据类型,进行 byType 模式的自动装配。
  5. autodetect —— 如果发现默认的构造函数,用 constructor 模式,否则,用 byType 模式。

spring 之 AOP

Advice

需要CGLIB2库 据搜索说是因为spring的aop的实现是基于该库

四种Advice 调用前 调用后 抛出异常 围绕,通过java实现spring的对应interface的类A,再通过xml配置target要切入的类B 和用来切入A 即可对指定类进行切入.deamo:

1
2
3
4
5
6
7
8
<bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="customerService" />
<property name="interceptorNames">
<list>
<value>hijackAroundMethodBean</value>
</list>
</property>
</bean>

Pointcut & Advisor

在上面的基础上再用 这两个 可以对指定的function才做切入

  • Advice:向程序内部注入的代码。
  • Pointcut:注入 Advice 的位置,切入点,一般为某方法。
  • Advisor: Advice 和 Pointcut 的结合单元,以便将 Advice 和 Pointcut 分开实现灵活配置。

auto proxy

代替ProxyFactoryBean用BeanNameAutoProxyCreator来自动批量切面,demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>customerAdvisor</value>
</list>
</property>
</bean>

AspectJ

又是对上面的 美化/简化

  • @Before
  • @After
  • @AfterReturning
  • @AfterThrowing
  • @Around

Java 整理

core java

##《Java项目开发全程实录 第3版》个人整理

涉及知识一览

按层次

其它

按目录

  1. SQL Server 2000, PowerDesigner
  2. JavaDB
  3. Hibernate Oracle
  4. SQL Server 2005, Visio
  5. SQL Server 2000
  6. JavaDB, 短信猫 Java Mail
  7. Hibernate, Spring
  8. SQL Server 2005
  9. no Swing, jsp, javaBean, SQL Server 2000, Tomcat, Proxool
  10. Socket, thread

TODO

IoC

AOP

Spring

Swing

个人账目管理

Minimum_maintenance.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

//template
#include<iostream>
#include<cstdlib>
#include<assert.h>
using namespace std;
struct max_select{
int p;
int d;
double v;
bool operator > (const max_select & other) const {
return v > other.v;
}
bool operator < (const max_select & other) const {
return v < other.v;
}
bool operator == (const max_select & other) const {
return v == other.v;
}
};

template <class T>
class Minimum_maintenance {
private:
T * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
int * _fakedeepcopy ;
public:
Minimum_maintenance(){
cout<<"NOT SUPPORT"<<endl;
assert(0);
}
Minimum_maintenance(int s){
if(s < 1)//protect
s = 1;
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[s];
_stack[1] = new T[s];
_order = new int[s];
_fakedeepcopy = new int [1] ;
printf("new (%08x)\n",this);
printf(" _stack[0] = (%08x)\n",_stack[0]);
printf(" _stack[1] = (%08x)\n",_stack[1]);
printf(" _order = (%08x)\n",_order);
_fakedeepcopy[0] = 0;
}
Minimum_maintenance(const Minimum_maintenance& copy){
_stack[0] = copy._stack[0];
_stack[1] = copy._stack[1];
_iter [0] = copy._iter [0];
_iter [1] = copy._iter [1];
_order = copy._order;
_fakedeepcopy = copy._fakedeepcopy;
_fakedeepcopy[0]++;
printf("Fake deepcopy %08x => %08x\n",&copy,this);
}
~Minimum_maintenance(){
printf("free(%08x)\n",this);
printf(" _fakedeepcopy = %d\n",_fakedeepcopy[0]);
printf(" _stack[0] = (%08x)\n",_stack[0]);
printf(" _stack[1] = (%08x)\n",_stack[1]);
printf(" _order = (%08x)\n",_order);
if(!_fakedeepcopy[0]){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}else{
_fakedeepcopy[0]--;
}
cout<<"free() finished"<<endl;
}
void push(const T & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1] > ms){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(T & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
bool const empty(){
return _iter[0] == 0;
}
};

int main(){
int i;
Minimum_maintenance<max_select> mm(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))//mm.empty()
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old1.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// just run
#include<iostream>
#include<cstdlib>
using namespace std;
class MinimumMaintenance {
private:
int * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
MinimumMaintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new int[3*s];
_stack[1] = new int[3*s];
_order = new int[s];
}
~MinimumMaintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void push(int p,int d,int v){
int i;
if(_iter[0] == 0 || _stack[0][3*(_iter[0] - 1)+2] > v){
i = 0;
}else{
i = 1;
}
_stack[i][3*_iter[i] ] = p;
_stack[i][3*_iter[i] + 1] = d;
_stack[i][3*_iter[i] + 2] = v;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(int & p,int & d,int &v){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
p = _stack[0][ 3 * _iter[0] - 3];
d = _stack[0][ 3 * _iter[0] - 2];
v = _stack[0][ 3 * _iter[0] - 1];
return true;
}
};
int main(){
int i;
MinimumMaintenance mm(20);
for( i = 0; i < 20 ; i ++){
int in = rand();
cout<<in<<endl<<"\t";
mm.push(1,1,in);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
int a,b,c;
if(mm.top(a,b,c))
cout<<c<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old2.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//struct
#include<iostream>
#include<cstdlib>
using namespace std;
struct max_select{
int p;
int d;
double v;
};
class Minimum_maintenance {
private:
max_select * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
Minimum_maintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new max_select[s];
_stack[1] = new max_select[s];
_order = new int[s];
}
~Minimum_maintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void push(const max_select & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1].v > ms.v){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(max_select & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
};
int main(){
int i;
Minimum_maintenance mm(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old3.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//operator
#include<iostream>
#include<cstdlib>
using namespace std;
struct max_select{
int p;
int d;
double v;
bool operator > (const max_select & other) const {
return v > other.v;
}
bool operator < (const max_select & other) const {
return v < other.v;
}
bool operator == (const max_select & other) const {
return v == other.v;
}
};
class Minimum_maintenance {
private:
max_select * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
Minimum_maintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new max_select[s];
_stack[1] = new max_select[s];
_order = new int[s];
}
~Minimum_maintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void push(const max_select & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1] > ms){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(max_select & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
};
int main(){
int i;
Minimum_maintenance mm(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old4.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//template
#include<iostream>
#include<cstdlib>
using namespace std;
struct max_select{
int p;
int d;
double v;
bool operator > (const max_select & other) const {
return v > other.v;
}
bool operator < (const max_select & other) const {
return v < other.v;
}
bool operator == (const max_select & other) const {
return v == other.v;
}
};

template <class T>
class Minimum_maintenance {
private:
T * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
Minimum_maintenance(){
// CHANGE?
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[1];
_stack[1] = new T[1];
_order = new int[1];
}
Minimum_maintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[s];
_stack[1] = new T[s];
_order = new int[s];
}
~Minimum_maintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void resize(int s){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[s];
_stack[1] = new T[s];
_order = new int[s];
}
void push(const T & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1] > ms){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(T & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
bool empty(){
return _iter[0] == 0;
}
};
int main(){
int i;
Minimum_maintenance<max_select> mm;
mm.resize(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))//mm.empty()
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

permutation_traversal.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//10 - 0.2s
#include<iostream>
using namespace std;

int pt_s;

void ptdemo(unsigned int pt_bits){
if(pt_bits == (1<<pt_s) - 1)
return ;
unsigned int i;
for(i = 0; i < pt_s ; ++i){
if( pt_bits & (1<<i) )
continue ;
//cout<<i<<endl;
int debug = i;
ptdemo(pt_bits | (1<<i));
}
return ;
}
int main(){
pt_s = 10;
int v = 0;
ptdemo(v);
return 0;
}

permutation_traversal.old1.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//10 - 11.588 
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
stack<pair<vector<int>::iterator,int>>visitstack; // to boost list?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li,const stack<pair<vector<int>::iterator,int>>&vs)
:left_index(li),visitstack(vs){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
if(iter == left_index.end())
return ;
++iter;
}

bool const valid(){
return iter != left_index.end();
}

int getnum(){
return visitstack.size();
}

int const getvalue(){
return iter != left_index.end() ? *iter : -1;
}
void push(){
if(iter == left_index.end())
return ;
visitstack.push(make_pair(iter,*iter));
left_index.erase(iter);
}
void pop(){
if(visitstack.empty())
return ;
pair<vector<int>::iterator,int> p = visitstack.top();
left_index.insert(p.first,p.second);
visitstack.pop();
}

Permutation_traversal * isolate(){// careful about memory overflow
return new Permutation_traversal(left_index,visitstack);
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
pt.push();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
pt.pop();
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old1.min.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// ,min.cpp use less check
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
stack<pair<vector<int>::iterator,int>>visitstack; // to boost list?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li,const stack<pair<vector<int>::iterator,int>>&vs)
:left_index(li),visitstack(vs){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
++iter;
}

bool const valid(){
return iter != left_index.end();
}

int const getvalue(){
return *iter;
}
void push(){
visitstack.push(make_pair(iter,*iter));
left_index.erase(iter);
}
void pop(){
pair<vector<int>::iterator,int> p = visitstack.top();
left_index.insert(p.first,p.second);
visitstack.pop();
}

Permutation_traversal * isolate(){// careful about memory overflow
return new Permutation_traversal(left_index,visitstack);
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
cout<<pt.getvalue()<<endl;
pt.push();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
pt.pop();
}
return ;
}
int main(){
Permutation_traversal pt(5);
ptdemo(pt);
return 0;
}

permutation_traversal.old2.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//10 4.469s
#include<iostream>
#include<vector>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li)
:left_index(li){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
if(iter == left_index.end())
return ;
++iter;
}

bool const valid(){
return iter != left_index.end();
}


int const getvalue(){
return iter != left_index.end() ? *iter : -1;
}

Permutation_traversal * isolate(){// careful about memory overflow
if(iter == left_index.end())
return NULL;
vector<int>::iterator tmp_iter = iter;
int tmp_val = *iter;
left_index.erase(iter);
Permutation_traversal * newpt = new Permutation_traversal(left_index);
left_index.insert(tmp_iter,tmp_val);
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-left_index.size();
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old2.min.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li)
:left_index(li){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
++iter;
}

bool const valid(){
return iter != left_index.end();
}


int const getvalue(){
return *iter;
}

Permutation_traversal * isolate(){// careful about memory overflow
vector<int>::iterator tmp_iter = iter;
int tmp_val = *iter;
left_index.erase(iter);
Permutation_traversal * newpt = new Permutation_traversal(left_index);
left_index.insert(tmp_iter,tmp_val);
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-left_index.size();
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
cout<<pt.getvalue()<<endl;
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(5);
ptdemo(pt);
return 0;
}

permutation_traversal.old3.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//10 - 0.927s
#include<iostream>
using namespace std;

class Permutation_traversal{
protected:
int * left_index; // to boost vector?
int size;
int iter;
Permutation_traversal(){
}
public:
Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
for(int i=0;i<s;i++){
left_index[i]=i;
}
}
~Permutation_traversal(){
delete [] left_index;
}
bool const empty(){
return size == 0;
}
void next(){
if(iter == size)
return ;
++iter;
}

bool const valid(){
return iter != size;
}

int const getvalue(){
return iter != size ? left_index[iter] : -1;
}

Permutation_traversal * isolate(){// careful about memory overflow
if(iter == size)
return NULL;
Permutation_traversal * newpt = new Permutation_traversal();
newpt->left_index = new int[size-1];
newpt->size = 0;
newpt->iter = 0;
for(int it = 0 ; it < size ; ++it){
if(it == iter)
continue;
newpt->left_index[newpt->size++] = left_index[it];
}
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old3.min.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
int * left_index; // to boost vector?
int size;
int iter;
Permutation_traversal(){
}
public:
Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
for(int i=0;i<s;i++){
left_index[i]=i;
}
}
~Permutation_traversal(){
delete [] left_index;
}
bool const empty(){
return size == 0;
}
void next(){
++iter;
}

bool const valid(){
return iter != size;
}

int const getvalue(){
return left_index[iter];
}

Permutation_traversal * isolate(){// careful about memory overflow
Permutation_traversal * newpt = new Permutation_traversal();
newpt->left_index = new int[size-1];
newpt->size = 0;
newpt->iter = 0;
for(int it = 0 ; it < size ; ++it){
if(it == iter)
continue;
newpt->left_index[newpt->size++] = left_index[it];
}
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
cout<<pt.getvalue()<<endl;
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(5);
ptdemo(pt);
return 0;
}

permutation_traversal.old4.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//10 - 0.581s
#include<iostream>
using namespace std;

class Permutation_traversal{
private:
class Child_Permutation_traversal{
public:
int * left_index; // to boost vector?
int size;
int iter;
Child_Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
}
~Child_Permutation_traversal(){
delete [] left_index;
}
};

Child_Permutation_traversal ** cpt;
int size;
int depth;
public:
Permutation_traversal(int s)
:size(s){
cpt = new Child_Permutation_traversal * [s + 1];
int i;
for(i = 0; i <= s; i++){
cpt[i] = new Child_Permutation_traversal(s-i);
}
for(i = 0; i < s; i++){
cpt[0]->left_index[i]=i;
}
depth = 0;
}
~Permutation_traversal(){
for(int i=0;i<=size;i++){
delete cpt[i];
}
delete [] cpt;
}
bool const empty(){
return cpt[depth]->size == 0;
}
void next(){
if(cpt[depth]->iter == cpt[depth]->size)
return ;
++(cpt[depth]->iter);
}

bool const valid(){
return cpt[depth]->iter != cpt[depth]->size;
}

int const getvalue(){
return cpt[depth]->iter != cpt[depth]->size ? cpt[depth]->left_index[cpt[depth]->iter] : -1;
}

void select(){
if(cpt[depth]->iter == cpt[depth]->size)
return ;
int newdepth = depth + 1;
cpt[newdepth]->size = 0;
cpt[newdepth]->iter = 0;
for(int it = 0,itlimit=cpt[depth]->size ; it < itlimit ; ++it){
if(it == cpt[depth]->iter)
continue;
cpt[newdepth]->left_index[cpt[newdepth]->size++] = cpt[depth]->left_index[it];
}
depth = newdepth;
}

void unselect(){
if(depth > 0)
--depth;
}

int getnum(){
return 5-cpt[depth]->size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
pt.select();
ptdemo(pt);
pt.unselect();
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old4.min.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//10 - 0.472s
#include<iostream>
using namespace std;

class Permutation_traversal{
private:
class Child_Permutation_traversal{
public:
int * left_index; // to boost vector?
int size;
int iter;
Child_Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
}
~Child_Permutation_traversal(){
delete [] left_index;
}
};

Child_Permutation_traversal ** cpt;
int size;
int depth;
public:
Permutation_traversal(int s)
:size(s){
cpt = new Child_Permutation_traversal * [s + 1];
int i;
for(i = 0; i <= s; i++){
cpt[i] = new Child_Permutation_traversal(s-i);
}
for(i = 0; i < s; i++){
cpt[0]->left_index[i]=i;
}
depth = 0;
}
~Permutation_traversal(){
for(int i=0;i<=size;i++){
delete cpt[i];
}
delete [] cpt;
}
bool const empty(){
return cpt[depth]->size == 0;
}
void next(){
++(cpt[depth]->iter);
}

bool const valid(){
return cpt[depth]->iter != cpt[depth]->size;
}

int const getvalue(){
return cpt[depth]->left_index[cpt[depth]->iter];
}

void select(){
int newdepth = depth + 1;
cpt[newdepth]->size = 0;
cpt[newdepth]->iter = 0;
for(int it = 0,itlimit=cpt[depth]->size ; it < itlimit ; ++it){
if(it == cpt[depth]->iter)
continue;
cpt[newdepth]->left_index[cpt[newdepth]->size++] = cpt[depth]->left_index[it];
}
depth = newdepth;
}

void unselect(){
--depth;
}

int getnum(){
return 5-cpt[depth]->size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
pt.select();
ptdemo(pt);
pt.unselect();
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# coding: utf-8

__version__ = '1.1.0'
__author__ = 'Zhu Jianqi (heloowird@gmail.com)'

'''
以关键词收集新浪微博
'''
import requests
import wx
import csv
import codecs
import sys
import urllib
import urllib2
import re
import json
import hashlib
import os
import time
import datetime
import random
from lxml import etree
import logging
import gzip
from StringIO import StringIO

class CollectData():
"""数据收集类
利用微博高级搜索功能,按关键字搜集一定时间范围内的微博。

大体思路:构造URL,爬取网页,然后解析网页中的微博ID。后续利用微博API进行数据入库。本程序只负责收集微博的ID。

登陆新浪微博,进入高级搜索,输入关键字”空气污染“,选择”实时“,时间为”2013-07-02-2:2013-07-09-2“,地区为”北京“,之后发送请求会发现地址栏变为如下:
http://s.weibo.com/wb/%25E7%25A9%25BA%25E6%25B0%2594%25E6%25B1%25A1%25E6%259F%2593&xsort=time&region=custom:11:1000&timescope=custom:2013-07-02-2:2013-07-09-2&Refer=g

是不是很长,其实很简单。
固定地址部分:http://s.weibo.com/wb/
关键字二次UTF-8编码:%25E7%25A9%25BA%25E6%25B0%2594%25E6%25B1%25A1%25E6%259F%2593
排序为“实时”:xsort=time
搜索地区:region=custom:11:1000
搜索时间范围:timescope=custom:2013-07-02-2:2013-07-09-2
可忽略项:Refer=g
显示类似微博:nodup=1 注:这个选项可多收集微博,建议加上。默认不加此参数,省略了部分相似微博。
某次请求的页数:page=1

另外,高级搜索最多返回50页微博,那么时间间隔设置最小为宜。所以该类设置为搜集一定时间段内最多50页微博。
"""
def __init__(self, keyword, startTime, savedir, interval='50', flag=True, begin_url_per = "http://s.weibo.com/weibo/"):
self.begin_url_per = begin_url_per #设置固定地址部分,默认为"http://s.weibo.com/weibo/",或者"http://s.weibo.com/wb/"
self.setKeyword(keyword) #设置关键字
self.setStartTimescope(startTime) #设置搜索的开始时间
# self.setRegion(region) #设置搜索区域
self.setSave_dir(savedir) #设置结果的存储目录
self.setInterval(interval) #设置邻近网页请求之间的基础时间间隔(注意:过于频繁会被认为是机器人)
self.setFlag(flag) #设置
self.logger = logging.getLogger('main.CollectData') #初始化日志

##设置关键字
##关键字需解码
def setKeyword(self, keyword):
#self.keyword = keyword.decode('GBK').encode("utf-8")
self.keyword = keyword
print 'twice encode:',self.getKeyWord()

##设置起始范围,间隔为1小时
##格式为:yyyy-mm-dd-HH
def setStartTimescope(self, startTime):
if not (startTime == '-'):
self.timescope = startTime + ":" + startTime
else:
self.timescope = '-'

# ##设置搜索地区
# def setRegion(self, region):
# self.region = region

##设置结果的存储目录
def setSave_dir(self, save_dir):
self.save_dir = save_dir
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)

##设置邻近网页请求之间的基础时间间隔
def setInterval(self, interval):
self.interval = int(interval)

##设置是否被认为机器人的标志。若为False,需要进入页面,手动输入验证码
def setFlag(self, flag):
self.flag = flag

##构建URL
def getURL(self):
return self.begin_url_per+self.getKeyWord()+"&typeall=1&suball=1"+"&timescope=custom:"+self.timescope+"&page="

##关键字需要进行两次urlencode
def getKeyWord(self):
once = urllib.urlencode({"kw":self.keyword})[3:]
return urllib.urlencode({"kw":once})[3:]

##爬取一次请求中的所有网页,最多返回50页
def download(self, url, maxTryNum=4):
csvFile = open(self.save_dir + os.sep + "weibo_kanbing.csv", "ab") #向结果文件中写微博ID
csvFile.write(codecs.BOM_UTF8)
content = csv.writer(csvFile, dialect='excel')
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
cookie = {'SINAGLOBAL':'3726160468139.8677.1489128973894', 'un':'18621677460', 'wvr':'6', 'SWB':'usrmdinst_12', 'SCF':'At4nsWXnBTiLQgwnhEdGW1ipfDRoyBYdEIpm4KN7_ZN3C0BxRlQeyX0sHoQOK6bDqLR6HeBBiwo6wRFXfObIvnc.', 'SUB':'_2A251wx_bDeRxGeNP7FIR9yjFwzyIHXVWuXYTrDV8PUNbmtBeLRjVkW8ia3o1WnWjknWq3t_Uh0UkKzBqsg..', 'SUBP':'0033WrSXqPxfM725Ws9jqgMF55529P9D9Wh_ODAX.pd3QJ6U3yvqGKET5JpX5KMhUgL.Fo-pS057S0q41h52dJLoIEUBBEXLxKqL1hnL1KnLxK-LBKeLB-zLxK-L1K5L1K2LxK-L12qLBoet', 'SUHB':'0vJ4Ss25HO1Ohu', 'ALF':'1521001227', 'SSOLoginState':'1489465228', '_s_tentry':'login.sina.com.cn', 'Apache':'7301168373695.357.1489465207066', 'ULV':'1489465207130:8:8:5:7301168373695.357.1489465207066:1489412710557', 'UOR':',,login.sina.com.cn', 'WBStorage':'02e13baf68409715|undefined'}

hasMore = True #某次请求可能少于50页,设置标记,判断是否还有下一页
isCaught = False #某次请求被认为是机器人,设置标记,判断是否被抓住。抓住后,需要复制log中的文件,进入页面,输入验证码
filter = set([]) #过滤重复的微博ID

i = 1 #记录本次请求所返回的页数
while hasMore and i < 51 and (not isCaught): #最多返回50页,对每页进行解析,并写入结果文件
source_url = url + str(i) #构建某页的URL
data = '' #存储该页的网页数据
goon = True #网络中断标记

##网络不好的情况,试着尝试请求三次
for tryNum in range(maxTryNum):
try:
# set header http://stackoverflow.com/questions/385262/how-do-i-send-a-custom-header-with-urllib2-in-a-http-request
# see this http://stackoverflow.com/questions/1653591/python-urllib2-response-header , so you can see 'gzip' in response header with urllib2.urlopen(URL).info()
# and this http://stackoverflow.com/questions/3947120/does-python-urllib2-automatically-uncompress-gzip-data-fetched-from-webpage teach you how to decode gzip
#
#r = requests.get(source_url, cookies=cookie, headers=headers, timeout=12)
send_headers = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding":"gzip, deflate, sdch",
"Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
#"Cookie":"cookies here"
"Host":"s.weibo.com",
"Pragma":"no-cache",
"Referer":"http://s.weibo.com/",
"Upgrade-Insecure-Requests":"1",
"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
}
req = urllib2.Request(source_url , headers=send_headers)
r = urllib2.urlopen(req)
if r.info().get('Content-Encoding') == 'gzip':
buf = StringIO(r.read())
f = gzip.GzipFile(fileobj=buf)
html = f.read()
else:
html = r.read()
data = html
#print data
break
except:
if tryNum < (maxTryNum-1):
time.sleep(10)
else:
print 'Internet Connect Error!'
self.logger.error('Internet Connect Error!')
self.logger.info('filePath: ' + self.save_dir)
self.logger.info('url: ' + source_url)
self.logger.info('fileNum: ' + str(fileNum))
self.logger.info('page: ' + str(i))
self.flag = False
goon = False
break
if goon:
lines = data.splitlines()
isCaught = True
for line in lines:
## 判断是否有微博内容,出现这一行,则说明没有被认为是机器人
if line.startswith('<script>STK && STK.pageletM && STK.pageletM.view({"pid":"pl_weibo_direct"'):
isCaught = False
n = line.find('html":"')
if n > 0:
j = line[n + 7: -12].encode("utf-8").decode('unicode_escape').encode("utf-8").replace("\\", "").decode('utf-8')
## 没有更多结果页面
if (j.find('<div class="search_noresult">') > 0):
hasMore = False
## 有结果的页面
else:
page = etree.HTML(j)
comment_box = page.xpath("//div[@action-type=\"feed_list_item\"]")
for each_comment in comment_box:
comment_time = each_comment.xpath(".//div[@class=\"feed_from W_textb\"]/a/@title")
comment_text_list = each_comment.xpath(".//p[@class='comment_txt']")
comment_text = []
for eachtext in comment_text_list:
comment_text = 'r'.join(eachtext.xpath(".//text()"))
comment_text = comment_text.replace(' ','').replace('\n', '').replace('\r', ' ')
comment_text = comment_text.encode('utf8')
if (comment_text != 'None' and comment_text not in filter):
filter.add(comment_text)
content.writerow([comment_time[0], comment_text])
# weibo = page.xpath("//div[@class=\"feed_from W_textb\"])
# for weibo_time, weibo_content in weibo:
# weibo_time = weibo_time.xpath("./[@class=\"feed_from W_textb\"]/a/@title")
# concept = 'r'.join(weibo_content.xpath("./text()"))
# concept = concept.replace(' ','').replace('\n','').replace('\r',' ')
# concept = concept.encode('utf8')
# if (concept != 'None' and concept not in filter):
# filter.add(concept)
# content.writerow([weibo_time, concept])

# dls_id = page.xpath("//div[@class=\"feed_from W_textb\"]/a/@title")
# for dl_id in dls_id:
# # mid = str(dl_id.attrib.get('nick-name'))
# dl_id = dl_id.encode('utf8')
# if (dl_id != 'None' and dl_id not in mid_filter):
# mid_filter.add(dl_id)
# content.writerow([dl_id])
#
# dls_text = page.xpath("//p[@class='comment_txt']")
# for dl_text in dls_text:
# concept = 'r'.join(dl_text.xpath("./text()"))
# concept = concept.replace(' ','').replace('\n','').replace('\r',' ')
# concept = concept.encode('utf8')
# if (concept != 'None' and concept not in mid_filter):
# mid_filter.add(concept)
# content.writerow([concept])
# content.writerow('\n')
# if (concept != 'None' and concept not in mid_filter):
# mid_filter.add(concept)
# content.write(concept)
# content.write('\n')
# print concept
# print "----------------------"
break
lines = None
## 处理被认为是机器人的情况
if isCaught:
print 'Be Caught!'
self.logger.error('Be Caught Error!')
self.logger.info('filePath: ' + self.save_dir)
self.logger.info('url: ' + source_url)
self.logger.info('fileNum: ' + str(fileNum))
self.logger.info('page:' + str(i))
data = None
self.flag = False
break
## 没有更多结果,结束该次请求,跳到下一个请求
if not hasMore:
print 'No More Results!'
if i == 1:
time.sleep(random.randint(55,75))
else:
time.sleep(15)
data = None
break
i += 1
## 设置两个邻近URL请求之间的随机休眠时间,防止Be Caught。目前没有模拟登陆
# sleeptime_one = random.randint(self.interval-30,self.interval-10)
# sleeptime_two = random.randint(self.interval+10,self.interval+30)
# if i%2 == 0:
# sleeptime = sleeptime_two
# else:
# sleeptime = sleeptime_one
# print 'sleeping ' + str(sleeptime) + ' seconds...'
# time.sleep(sleeptime)
else:
break
csvFile.close()
csvFile = None

##改变搜索的时间范围,有利于获取最多的数据
def getTimescope(self, perTimescope, hours):
if not (perTimescope=='-'):
times_list = perTimescope.split(':')
start_datetime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(times_list[-1],"%Y-%m-%d-%H")))
start_new_datetime = start_datetime + datetime.timedelta(seconds = 3600)
end_new_datetime = start_new_datetime + datetime.timedelta(seconds = 3600*(hours-1))
start_str = start_new_datetime.strftime("%Y-%m-%d-%H")
end_str = end_new_datetime.strftime("%Y-%m-%d-%H")
return start_str + ":" + end_str
else:
return '-'

def main():
logger = logging.getLogger('main')
logFile = './collect.log'
logger.setLevel(logging.DEBUG)
filehandler = logging.FileHandler(logFile)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)

while True:
## 接受键盘输入
keyword = raw_input('Enter the keyword(type \'quit\' to exit ):')
if keyword == 'quit':
sys.exit()
startTime = raw_input('Enter the start time(Format:YYYY-mm-dd-HH):')
# region = raw_input('Enter the region([BJ]11:1000,[SH]31:1000,[GZ]44:1,[CD]51:1):')
savedir = raw_input('Enter the save directory(Like C://data//):')
interval = raw_input('Enter the time interval( >30 and deafult:50):')

##实例化收集类,收集指定关键字和起始时间的微博
cd = CollectData(keyword, startTime, savedir, interval)
while cd.flag:
print cd.timescope
logger.info(cd.timescope)
url = cd.getURL()
cd.download(url)
cd.timescope = cd.getTimescope(cd.timescope,1) #改变搜索的时间,到下一个小时
else:
cd = None
print '-----------------------------------------------------'
print '-----------------------------------------------------'
else:
logger.removeHandler(filehandler)
logger = None
if __name__ == '__main__':
main()
0%