Quantcast
Channel: CSDN博客推荐文章
Viewing all 35570 articles
Browse latest View live

Sicily 6137. Removing Brackets

$
0
0

6137. Removing Brackets

Constraints

Time Limit: 1 secs, Memory Limit: 256 MB

Description

Mirko was bored at his chemistry class, so he played Bomb Switcher on his cell phone. Unfortunately, he was spotted and was given a ridiculously heavy assignment for homework. For a given valid math expression with brackets, he must find all different expressions that can be obtained by removing valid pairs of brackets from the original expression. Two expressions are different if there is a character at which they differ.
For example, given (2+(2*2)+2), one can get (2+2*2+2), 2+(2*2)+2, and 2+2*2+2. (2+2*2)+2 and 2+(2*2+2) can?t be reached, since we would have to remove pairs of brackets that are not valid. More than one pairs of brackets can surround the same part of the expression.

Input

The first and only line of input contains one valid mathematical expression composed of nonnegative integers, basic arithmetic operations denoted with characters ?+?, ?*?, ?-? and ?/?, and brackets ?(? and ?)?.
Given expression won?t have more than 200 characters, and will have at least one, and no more than 10 pairs of brackets. Each expression is guaranteed to have at least one pair of brackets.
 

Output

Output all different expressions that can be obtained by removing valid pairs of brackets, sorted lexicographically.

Sample Input

样例1:
(0/(0))
样例2:
(2+(2*2)+2)
样例3:
(1+(2*(3+4)))

Sample Output

样例1:
(0/0) 
0/(0) 
0/0
样例2:
(2+2*2+2) 
2+(2*2)+2 
2+2*2+2
样例3:
(1+(2*3+4)) 
(1+2*(3+4)) 
(1+2*3+4) 
1+(2*(3+4)) 
1+(2*3+4) 
1+2*(3+4) 
1+2*3+4

Problem Source

COCI 2012.4 2012年每周一赛第十一场

DFS,枚举所有,注意有可能会有((1 + 2))的情况;

#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;

string c[1050];//答案string数组
char ori_in[205];//原来读入的字符串,用于比较
char in[205];//不断在DFS中变换的字符串
int b_pos[11];//左括号位置
int to_b_pos[11];//与左括号位置对应的用括号位置
int counter = 0;//总共不同的答案数
int brackets = 0;//括号对数

bool was_here(int pos) {//检查是否已经出现过
    for (int i = 0; i < pos; i++) {
        if (c[i] == c[pos]) {
            return true;
        }
    }
    return false;
}

void push_in() {//存入答案数组
    for (int i = 0; i < (int)strlen(in); i++) {
        if (in[i] != ' ') {
            c[counter].push_back(in[i]);
        }
    }
    if (!was_here(counter)) {
        counter++;
    } else {
        c[counter].clear();
    }
}

void DFS(int pos) {
    
    if (pos == brackets) {
        if (strcmp(ori_in, in))
            push_in();
        return;
    }

    DFS(pos + 1);//当前位置括号不变
        
    in[b_pos[pos]] = ' ';
    in[to_b_pos[pos]] = ' ';
    DFS(pos + 1);//当前位置括号去掉
    in[b_pos[pos]] = '(';
    in[to_b_pos[pos]] = ')';
}

bool is_new(int pos, int count) {//计算括号数目的时候用于判断(是否已经出现过
    for (int i = 0; i < count; i++) {
        if (b_pos[i] == pos) {
            return false;
        }
    }
    return true;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin >> in;
    strcpy(ori_in, in);
    brackets = 0;
    for (int i = 0; i < (int)strlen(in); i++) {
        if (in[i] == '(') {
            brackets++;
        }
    }
    int k = 0;
    for (int i = 0; i < (int)strlen(in); i++) {
        if (in[i] == ')') {
            for (int j = i - 1; j >= 0; j--) {
                if (in[j] == '(' && is_new(j, k)) {
                    b_pos[k] = j;
                    to_b_pos[k++] = i;
                    break;
                }
            }
        }
    }
    DFS(0);
    sort(c, c + counter);//排序得字典序
    for (int i = 0; i < counter; i++) {
        cout << c[i] << endl;
    }
    return 0;
}


作者:u012925008 发表于2015/3/24 18:38:58 原文链接
阅读:69 评论:0 查看评论

关于tableview的一些bug

$
0
0

about tableview bug


内存压力而奔溃

原因:cell没有被复用

一般来说,对于cell的复用是这样子的:

关于cell的复用:这里根据屏幕的高度,先创建第一个cell,第二个cell。当tabbleview向上滑动的时候,第一个cell渐渐移除屏幕,创建第三个cell,从屏幕下方进入显示。当第一个cell全部移除屏幕的时候会进入复用池,第四个cell就会复用第一个cell。这里tablveiw会创建3个cell,然后其他的就会复用。

(1)cell xib上的设置

(2)代码里面设置表的cell,给cell添加identifier,cell xib和这个identifier要一致

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"starShowCell";
    StarShowTableViewCell *cell = [starTableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
       
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StarShowTableViewCell" owner:nil options:nil];
        for (id oneObject in nib) {
            if ([oneObject isKindOfClass:[StarShowTableViewCell class]]) {
                cell = (StarShowTableViewCell*)oneObject;
            }
        }
  
    }
 }

可我的问题是:

可是,我的代码里面这样子写,cell并没有复用,而是每次都创建了新的cell,每次都会进入if(cell==nil)里面去创建新的cell。
原因:StarShowTableViewCell *cell = [starTableView dequeueReusableCellWithIdentifier:identifier];
我用xib关联了一个starTableView,然后写了一个实例变量 uitableview *starTableView;这里拿到的tableview和我显示tableview不是一样的。本来当前页面只有一个tableview,但是代码里面有两个了。




erminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray insertObject:range:: Out of bounds'
*** First throw call stack:

数组越界。cell复用,没有重置数据。没有刷新reloaddata

使用tableview的时候老是出现cell的数据重复,是因为我们复用cell却没有重置数据。就像tableview你给了他数据,还要reloaddata才行。

- (void)awakeFromNib
{

}
-(void)setStarModel:(StarShowModel *)starModel{

    _starModel = starModel;

 }
  
-(void)layoutSubviews{

}







作者:u010241322 发表于2015/3/24 18:39:24 原文链接
阅读:68 评论:0 查看评论

iOS:UICollectionView的构建及使用

$
0
0

第一部分,三个协议方法,先介绍两个

<UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout > 

前两个的用法和tableView的很像,第三个是头视图尾视图的协议。
头视图尾视图,一样要写代理,写注册,缺少了就不行。
注册以后,就不需要再去管理复用的问题了。这点就很简单。这个如果用好的话,会非常的简单。很多事情迎刃而解,否则使用tableView的话,需要三个tableView一起滑动,彼此之间需要观察,一旦变化随之变化,用scroller 的ContentOffset 来控制滑动,非常不科学,用这个的话三个就一起滑动了。

第二部分,构建

先得创建一个layout,UICollectionViewFlowLayout  这个类型的
//创建布局对象
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//设置单元格的尺寸
flowLayout.itemSize = CGSizeMake(80, 80);
//设置头视图高度
flowLayout.headerReferenceSize = CGSizeMake(0, 30);
//flowlaout的属性,横向滑动
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//接下来就在创建collectionView的时候初始化,就很方便了(能直接带上layout)
_myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 200, 320, 280) collectionViewLayout:flowLayout];
_myCollectionView.tag = 200;
_myCollectionView.backgroundColor = [UIColor greenColor]; _myCollectionView.delegate = self;
_myCollectionView.dataSource = self;
//添加到主页面上去 
[self.view addSubview:_myCollectionView];
//collectionCell的注册
[_myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"myheheIdentifier"];
//collection头视图的注册   奇葩的地方来了,头视图也得注册
[_myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Identifierhead”];

#pragma mark -UICollectionViewDataSource
//指定组的个数 ,一个大组!!不是一排,是N多排组成的一个大组(与下面区分)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

//指定单元格的个数 ,这个是一个组里面有多少单元格,e.g : 一个单元格就是一张图片
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 10;
}

//构建单元格
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 200) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myheheIdentifier" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor purpleColor];
        return cell;
    }
}

//组的头视图创建
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Identifierhead" forIndexPath:indexPath];
    headView.backgroundColor = [UIColor blueColor];
    return headView;
}

//通过协议方法设置单元格尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat rd = arc4random()%90;
    return CGSizeMake(90, rd);
}


作者:u013243469 发表于2015/3/24 18:40:03 原文链接
阅读:75 评论:0 查看评论

Sicily 6136. Windows

$
0
0

6136. Windows

Constraints

Time Limit: 1 secs, Memory Limit: 256 MB

Description

Now that spring is here and the sun is shining bright, people are starting to lower their blinds. ?tefica is an elderly woman who likes to keep track of what other people in the neighbourhood are doing and then talk about it behind their backs. This year, she is particularly interested in who is lowering blinds in the building across the street, and how low are they lowering them.
We will represent each window with a 4 x 4 grid, with asteriskes representing lowered blinds. ?tefica can see a window in one of the following 5 states:

The building across the street has N windows at each of the M floors. Given the current building state, find out how many windows are in each of the 5 states shown above.

 

Input

The first line of input contains space separated integers M and N (1 ≤ M, N ≤ 100).
The following lines describe the current building state. Each window is represented with one of the 4 x 4 grids shown above, and windows are separated using character ?#?. See the example input for clarification. Building description will have exactly 5M + 1 lines each having 5N + 1 characters.

 

Output

Output should contain 5 space separated integers, number of windows for each type in order shown above. Sum of these numbers is M*N.

 

Sample Input

样例1:
1 2 
########### 
#....#****# 
#....#****# 
#....#....# 
#....#....# 
###########
样例2:
2 3 
################ 
#****#****#****# 
#****#****#****# 
#****#....#****# 
#....#....#****# 
################ 
#....#****#****# 
#....#****#....# 
#....#....#....# 
#....#....#....# 
################

Sample Output

样例1:
1 0 1 0 0
样例2:
1 1 2 1 1

Problem Source

COCI 2012.4 2012年每周一赛第十一场

// Problem#: 6136
// Submission#: 2811354
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <stdio.h>
#include <string.h>

char temp[5][501];
int num[5];

void judge(int col) {
    int counter = 0;
    for (int i = 1; i <= 4; i++) {
        if (temp[i][col] == '*') {
            counter++;
        }
    }
    num[counter]++;
}

int main() {
    int h, w;
    scanf("%d %d\n", &h, &w);
    memset(num, 0, sizeof(num));
    while (h--) {
        for (int i = 0; i < 5; i++) {
            gets(temp[i]);
        }
        for (int i = 0; i < w; i++) {
            judge(i * 5 + 1);
        }
    }
    for (int i = 0; i < 5; i++) {
        if (i)
            printf(" ");
        printf("%d", num[i]);
    }
    printf("\n");
    return 0;
}                     


作者:u012925008 发表于2015/3/24 18:40:04 原文链接
阅读:60 评论:0 查看评论

Sicily 9160. ESEJ

$
0
0

9160. ESEJ

Constraints

Time Limit: 1 secs, Memory Limit: 256 MB

Description

Mirko's latest homework assignment is writing an essay. However, he finds writing essays so boring that, after working for two hours, he realized that all he has written are N long words consisting entirely of letters A and B. Having accepted that he will never finish the essay in time, poor Mirko has decided to at least have some fun with it by counting nice words.
Mirko is connecting pairs of identical letters (A with A, B with B) by drawing arches above the word. A given word is nice if each letter can be connected to exactly one other letter in such a way that no two arches intersect. Help Mirko count how many words are nice.

Input

The first line of input contains the positive integer N (1 ≤ N ≤ 100), the number of words written down by Mirko.
Each of the following N lines contains a single word consisting of letters A and B, with length between 2 and 100 000, inclusive. The sum of lengths of all words doesn't exceed 1 000 000.

Output

The first and only line of output must contain the number of nice words.

Sample Input

3
ABAB
AABB
ABBA

Sample Output

2

Problem Source

2013年每周一赛第10场/COCI 2013.1

感觉跟那道夫妻匹配题很像:

发现用gets读字符串比scanf快;

#include <stdio.h>
#include <stack>
using namespace std;

int main() {
    int counter = 0, n;
    scanf("%d\n", &n);
    char temp[100001];
    while (n--) {
        stack<char> s;
        gets(temp);
        for (int i = 0; temp[i] != '\0'; i++) {
            if (s.empty()) {
                s.push(temp[i]);
            } else {
                if (temp[i] == s.top()) {
                    s.pop();
                } else {
                    s.push(temp[i]);
                }
            }
        }
        if (s.empty()) {
            counter++;
        }
    }
    printf("%d\n", counter);
    return 0;
}
作者:u012925008 发表于2015/3/24 18:40:50 原文链接
阅读:33 评论:0 查看评论

炉温控制(Keil代码+Proteus仿真+Matlab仿真)

$
0
0

转眼间大三了,课程设计周:炉温控制实验。那好吧,挺简单的,不过还是要做下去。认真做的话能学到不少东西,做的深入的话要用到三款软件:KEIL  PROTEUS  MATLAB。

做完了仿真和源代码,测试结束。想不来了,不过估计可爱的老师会不同意,必须在这坐两个星期,没事做,来写一波博客记录下吧。

 

-- . -- duang~

 

先把炉温控制实验的要求贴出来:

 

课题要求 (这些都是废话,一般没看的习惯。。。)

1 了解温度控制系统的构成,熟悉各环节的工作原理。

2.建立炉温控制系统的数学模型。

3.控制算法要求使用PID算法,除了应用基本PID算法进行控制外,要求对该PID控制算法进行改进。分析改进前后的性能指标,并进行相应的理论分析。

4 完成PID参数整定,调试出稳定的温度控制系统,观察并分析PID整定规律,保存最佳的整定参数与控制曲线图。

5. 设计编写采样、滤波、PID控制及优化算法等相关程序。 

6.  实物的要求忘了....

 

随便看看,要求就行啦,一看实验名字就都懂的。

看见学校发了51单片机来做,Wow,心里那个激动啊,大一是捧在身心玩了好几个月的片子,启蒙老师~

 

 

 

First Blood:proteus仿真

拿到51做东西,第一件事情自然是安装proteus,坐出炉温控制的仿真,仿真做出来,调试代码的时候真的很舒服,正所谓磨刀不误砍柴工

安装proteus:

百度云盘分享一下:http://pan.baidu.com/s/1hq7Z2S0

安装方法:

1.解压该压缩包,打开安装程序P7.8sp2。
2.一直点击下一步,然后选择Use a locally installed Licence Key。
3.其实这里的两个都可以选的,你只需要链接的第一幅图中的Licence.lxk(注意。这里的Licence是过期的,等安装完成之后我们还需要升级才能打开proteus。)
4.找到并Install,最后close。
5.一直下一步,直到安装结束。
6.安装结束后,打开图1中的破解1.0升级并点击升级其Licence。至此,proteus完全安装完毕。
7.打开解压文件中的仿真图 lxk.DSN
8.下面是我做好的仿真。接下来,我会详细说说仿真图怎么做。
 
 
Proteus仿真入门教学(以本次试验为例):
1.打开软件后,点击File下面的小图标新建一个Design。
2.做仿真,第一步自然要选取需要用到的元件。那么,点击Library选项里的Pick Device
这次试验要用到的元件有:
7SEG-MPX4-CA
AT89C52
BUTTON
BUZZER
CAP
CRYSTAL
DS18B20
LED_GREEN
LED_RED
NOT
PNP
RES
RESPACK-8
3.点击左边小按钮,进入元件模式,再左键单击一下右边的Devices,就可以进行放置元件。大家可以根据自己的喜好放置元件,多多做做仿真就能知道怎么放置比较美观并且自己不容易混乱。
4.放置好元件之后进行连线,该线就是现实中的导电线。如果不会可以打开我的仿真图借鉴。另外仿真中有一个技巧就是可以不练线,直接给引脚编号,同样的编号其实就意味着他们是连接在一起的。  进入LBL模式,进行编号。
5.需要修改参数的话,双击元件即可修改相应的参数。(双击51单片机,可以给它烧录进去生成的HEX文件,这也是仿真和代码的精髓之处,避免了实物调试的麻烦。)相信大家很快就会掌握这个简单易学又实用的仿真软件。
 
 
 
 
 
 
Double Kill:keil代码
仿真完成后,就可以开始写代码了。Keil可以生成Hex文件,Hex文件可以放入proteus仿真图中的51单片机进行联合调试。
 
安装Keil For 51:
简单的科普一下keil,keil估计是每一个单片机初学者的启蒙软件。但是keil并不仅仅用于51,他有非常大兼容性,可以写很多片子的代码。除了Keil for 51之外,还有keil for arm。keil for 51的安装方法我也放了一份放在压缩包里面,打开就能看到。
安装方法:
1. 安装Keil C51 V9.00版本
2. 打开uVision4,点击File---License Management...,打开License Management窗口,复制右上角的CID
3. 打开注册机, 在CID窗口里填上刚刚复制的CID,其它设置不变
4. 点击Generate生成许可号,复制许可号
5. 将许可号复制到License Management窗口下部的New License ID Code,点击右侧的Add LIC
6. 若上方的Product显示的是PK51 Prof. Developers Kit即注册成功,Support Period为有效期,一般可以到30年左右,若有效期较短,可多次生成许可号重新注册。
 
Ps:有的人会奇怪,自己的keil哪怕不适用license也能写代码并编译代码,但是当你代码量写到很大很大的时候,过期的license就会限制你的代码大小,无法编译
 
Keil For 51 编程入门教学(以本次试验为例):
 
写代码这个活,必须是日常的积累,不是看一篇或者两篇教学就能掌握的,所以建议初学的同学直接拿代码修改修改,理解一下各个代码段和函数的作用。理解了再尝试自己写写。可以说,会改代码的人就已经算是入门了,哪怕平时做电赛做飞思卡尔做一些小项目的时候。
另外初学代码的人,一定要注意代码规范化。代码堆放的美观性,代码的可读性,代码的注释,都是一段优秀代码必不可缺少的。网上对此有非常多的讲解,建议大家有空好好看看。
 
这次的代码有两个关键点,解决这两个关键点自然毫无难处可言了。
第一:PID
	    //PID Calculate	by Li
		tempchange();
		get_temp();
		f_temp_new = f_temp;					//	 °
		f_temp_err = f_temp_new - f_temp_old;	//	 °		  升温 大于 0  降温 小于 0
		f_temp_rate = f_temp_err / 0.25;		    //   °/s
		f_temp_old = f_temp_new;				//   °
	    //
 
/********PID Calculate Hot Time************/
void PID(){
	hot_time = Canshu_P * (Set_Temp - f_temp_new * 10) + Canshu_D * f_temp_rate * 10;
}
第二:PWM
原理:51的PWM输出。自然要用到定时器操作,首先我们要确定周期,既然中断服务函数的进入时间是50ms,那么我们选择1s为一个周期,在这个周期内我们可以进行20次的翻转电平操作,也就是说我们可以生成1/20 2/20 3/20 4/20 ....................20/20的PWM方波。而这个占空比的入口参数,就是PID算法的结果。即为:hot_time;
void Timer0_ISR(void) interrupt  1      /*50ms中断服务程序*/
{
	TH0 = (65536 - 50000) / 256;
    TL0 = (65536 - 50000) % 256;		/*重装初值*/
	/******************PID闭环控制******************************/
	time ++ ;		  //time x 50ms
 	if(hot_time > 0){
 		hot_time --;
		RELAY = 0;		     //继电器工作
		LED_YELLOW = 0;		 //黄亮
	}
	if(hot_time <= 0){
		RELAY = 1;	         //继电器停止
		LED_YELLOW = 1;		 //黄灭
		hot_time = 0;
	}
	if(time == 20){		     //1秒一次
		time = 0;
		now_time ++;         //单片机内部计时
		if(Flag == 2){
			if(set_time > 0){
				set_time --; 
			}
		}
		if(now_time == 999){
			now_time = 0;
		}
	    //PID Calculate	by Li
		tempchange();
		get_temp();
		f_temp_new = f_temp;					//	 °
		f_temp_err = f_temp_new - f_temp_old;	//	 °		  升温 大于 0  降温 小于 0
		f_temp_rate = f_temp_err / 0.25;		    //   °/s
		f_temp_old = f_temp_new;				//   °
	    //
		PID();
	}
	/**********************************************************/
	/**********************检测按键****************************/
	if(SET == 0 && (Flag == 0 || Flag == 2)){
	   Flag = 1;
	   delay(180);
	}
	if(Flag == 1){										  //温度定好 运行
		if(ADD == 0){
			Set_Temp += 10;
			delay(180);
		}
		if(CUT == 0){
			if(Set_Temp >= 10)
				Set_Temp -= 10;
			delay(180);
		}
		if(END == 0){
		    Flag = 0;									  //预定温度运行
			delay(180);
		}
	}
	if(ADD == 0 && (Flag == 0 || Flag == 2)){
		Flag = 3;
		delay(180);
	}
	if(Flag == 2){
		if(set_time > 0){
			RELAY = 0;		     //继电器工作
			LED_YELLOW = 0;		 //黄亮	
		} else {
			RELAY = 1;	         //继电器停止
			LED_YELLOW = 1;		 //黄灭
		}
	}
	if(Flag == 3){										 //时间定好 运行
		if(ADD == 0){
		   set_time += 5;
		   delay(180);
		}
		if(CUT == 0){
		   if(set_time >= 5)
		  	 set_time -= 5;
		   delay(180);
		}
		if(END == 0){
		   Flag = 2;									  //预定时间运行
		   delay(180);
		}
	}
	/**********************************************************/
}

至于其他的控制都不是什么难事。比如LED,蜂鸣器,继电器。都是很简单的高低电平控制了。具体操作代码可以参考压缩包内的keil文件,有很详细的注释。
至于一些接线的硬件上的连接,比如PNP,DS18B20等的电路,可以参考Proteus里的仿真,原理等下次有空再写吧。不是什么难点,百度一下就有了。
 
 
 
 
 
 
triple kill:Simulink仿真
调试代码中的PID参数,其实我是一直没有做Simulink仿真的习惯,不过老师说不做不行,所以入门了一下,简单的做了一个仿真,但是关于这个的传递函数我不会求,求指导~
Malab Simulink的使用还是非常简单的,模块化编程,这一点和Dream Weaver很像,模块化编程真的是把编程这个很烦的事情大众化,简单化了。给发明这个的神点个赞。
 
Matlab 7 下载地址:
 

Matlab7.0安装教程

要配置环境变量,如下:右键我的电脑(计算机)——属性——高级系统设置——在高级选项卡中,点环境变量——在系统变量中,吧TEMP、TMP的路径改为C:\temp

在C盘下建一个临时文件夹(安装时用)
3.直接双击压缩包中的setup(注意不用解压缩)

所示在红线内属于序列号。有以下序列号可供选择:
Matlab 7 (R14) 注册码1:14-13299-56369-16360-32789-51027-35530-39910-50517-56079-43171-43696-14148-64597-46518-35191-10070-58980-25665-36629-51033-46438-01127-52395-28569-20030-38795-14563-11876-23292-58825-37547-05827-26397
Matlab 7 (R14) 注册码2:
14-58204-39252-07634-11570-16849-09455-22809-05445-13616-29058-08276-06885-12215-41987-21894-60423-57622-18647-58411-24238-20443-59027-07209-27706-28292-14609-15393-48293-13036-12293-43713-57876-43362
Matlab 7 (R14) 注册码3:
14-44889-04614-04275-46147-23559-43066-41714-23083-65272-04997-17469-27919-17226-59862-27901-53983-56217-20094-53460-62647-58166-24499-35558-19511-44882-53016-25658-61109-03776-34505-00776-15813-07183

接下来就可以使用matlab了。

可即使按照这样做仍然会出现一些问题,别急!是问题总会有解决的方法。
笔者结合多次安装matlab7.0现将问题解决方案总结如下:
步骤6,7,8均为注意事项,若照以上步骤安装成功可忽略6,7,8
1、运行安装exe时就弹出对话框不能安装。

解决方法:
更改:我的电脑>属性>高级>环境变量>,然后将TEMP和TMP的值都改为C:\temp
2、解压后仍有许多压缩文件,点击stup.exe时出现警告

The installer cannot read the mwinstall.dll file, This is probably due to a CD reader which canshowLinkBubble(this);returnfalse"href="http://www.mathworks.com/"target="_blank">http://www.mathworks.com/ for assistance.
解决方法:
你把安装文件夹复制到一个英文文件夹中,比如直接解压到C盘,点击setup.exe安装即可。很多国外软件放在有中文名的文件夹中运行,这是一个bug。比如win-tc对中文特别敏感。所以建议初学者将这些软件(包括MATLAB)都安装在C盘。

3、运行MATLAB时出现Runtime Error,症状如下:
runtime error
program:E:\MATLAB7\bin\win32\MATLAB.exe
this application has requested the runtime to terminate it in an unusual way. please contact the application's support team for more information
另一个对话框里边还有一串JAVA程序。
解决方法:
把电脑主题改成了WindowXP经典主题,再次运行,就OK了。
如果不想启用经典模式,也有另一种解决方法:点击桌面的matlab快捷方式,右键点击“属性”,,点兼容性,选择用兼容模式运行,例如用WIN2000运行就可以了!这下好了吧,即不换回你漂亮的主题,又可用matlab了
4、Matlab安装后可能会遇到这样的问题,打开后窗口出来了,但一会儿以后又自动关闭了! 解决方法:
、我的电脑—>属性—>高级—>环境变量.
②、在系统变量下面添加如下内容

点击新建,输入:
变量名:BLAS_VERSION
变量值
:C:\Matlab7\bin\win32\atlas_Athlon.dll
(变量值的第一个字母为你的MATLAB安装在那个盘的盘符名,如在C盘即为C:\Matlab7\bin\win32\atlas_Athlon.dll。在E盘即为:E:\Matlab7\bin\win32\atlas_Athlon.dll)

5、运行MATLAB时,窗口显示:The element type "name" must be terminated by the matching end-tag "".Could not parse the file: e:\matlab\toolbox\ccslink\ccslink\info.xml
解决方法:

、找到安装文件目录下的info.xml文件,路径为:C:\matlab\toolbox\ccslink\ccslink(以安装在C盘为例)
、用记事本方式打开info.xml,找到里面的一行Link for Code Composer Studio?/name>,然后把/name>改为就可以了。
6、安装MATLAB时,有一个对话框显示:To configure Real-Time Windows Target you must type 'rtwintgt -setup' in a MATLAB command window
解决方法:

在安装好的MATLAB窗口中输入:rtwintgt –setup,再回车。

 
细节性的安装教程如下(摘自):
 
安装教程.doc下载网址:
 
做好的Simulink仿真图下载网址:
其实Simulink很简单的,不需要像keil上一样,根据别人的修改。只需要记住以下三个步骤,就可以完成一套Simulink的仿真啦。(其实和proteus步骤差不多。)
1.打开matlab,点击该按钮控件打开Simulink。
2.查找并添加元件,元件名称大家可以自己看着图3中的元件名称查找。
3.连线,编译,开始仿真。和proteus的过程真的很像~
4.修改参数后,双击Scope示波器,Auto一下之后就可以看到输出波形,这套参数是不是很棒。
6.修改参数实例(修改step的参数。)双击打开Step设置,即可修改,因为温度最终老师要求设定在60度,所以将该项中的Final value设置为60.
Simulink我用的挺少的,在此只是对怎么搭建一个PID模型和调试PID参数进行简单的操作。
 
 
 
 
 
 
 
就这样吧,写完了,也还算详细具体吧,当然也遗漏了很多细节。缺什么大家留言说一下,有时间我再慢慢添加吧。大的工程项目其实也和这些小的简单的实验差不多,都是一样的步骤,一步一步来,不能操之过急,反而什么都学不会了。
 
 
 
                                                                                                                                                                                                                                         2015、03、27
                                                                                                                                                                                                                                            Themelody
作者:lxk7280 发表于2015/3/27 16:06:45 原文链接
阅读:108 评论:0 查看评论

leetcode || 43、Multiply Strings

$
0
0

problem:

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

Hide Tags
 Math String
将两个用字符串表示的大数相乘

thinking:

(1)用字符串表示大数相乘,可以不用考虑溢出的问题

(2)第一种方法比较笨重,直接模拟乘法(我在自己机器上测试没问题,提交时显示runtime error,郁闷)

class Solution {
public:
    string multiply(string num1, string num2) {
        vector<string> container;
        string ret;
        int length1=num1.size();
        int length2=num2.size();
        if(length2>length1)
        {
            string tmp=num1;
            num1=num2;
            num2=tmp;
        }

        int i=0;
        int index=length2-1;
        while(index>=0)
        {
            string res=string_multiply_char(num1,num2.at(index),i);
            container.push_back(res);
            index-- ;
            i++;
        }
        ret=string_add_atring(container);
        return ret;

    }
protected:
    string string_multiply_char(string str, char ch, int i)
    {
       cout<<str<<" * "<<ch<<" i "<<i<<endl;
        string ret;
        string tail;
        for(int j=0;j<i;j++)
            tail.push_back('0');
        int a=0;//jin wei
        int y=ch-'0';
        int count = str.size()-1;
        stack<char> _stack;
        while(count>=0)
        {
            int x=str.at(count)-'0';
            cout<<"char x: "<<x<<endl;
            int mid = x*y;
            char z = (mid+a)%10+'0';
            a=(mid+a)/10;
            _stack.push(z);
            count--;
        }
        if(a>0)
            _stack.push(a+'0');
        while(!_stack.empty())
        {
            ret.push_back(_stack.top());
            _stack.pop();
        }
        ret+=tail;
        cout<<" ret "<<ret<<endl;
        return ret;
    }

    string string_add_atring(vector<string> res)
    {
        string str1;
        string str2;
        if(res.size()<2)
            return str1;
          str1=res[0];
        for(int i=1;i<res.size();i++)
        {
           str2=res[i];
            cout<<str1<<"+"<<str2<<endl;
           int m=str1.size();
           int n=str2.size();
           int count = min(m,n);
           int a=0;
           stack<char> _stack;
           for(int j=0;j<count;j++)
           {
               int x=str1.at(m-j-1)-'0';
               int y=str2.at(n-j-1)-'0';
               char mid=(x+y+a)%10+'0';
               cout<<"char mid"<<mid<<endl;
               a =(x+y+a)/10;
               cout<<"jin wei "<<a<<endl;
               _stack.push(mid);
           }
           if(m>n)
           {
               for(int k=m-n-1;k>=0;k--)
               {
                   char mid1=a+str1.at(k);
                   cout<<" mid1 "<<mid1<<endl;
                   _stack.push(mid1);
                   a=0;
               }
           }
           else if(m<n)
           {
               for(int l=n-m-1;l>=0;l--)
               {
                   char mid2=a+str2.at(l);
                   cout<<"mid2 "<<mid2<<endl;
                   _stack.push(mid2);
                   a=0;
               }
           }
           else
           {
               if(a>0)
               _stack.push(a+'0');
           }
           str1.clear();
           while(!_stack.empty())
           {
               str1.push_back(_stack.top());
               _stack.pop();
           }

        }//for
        return str1;
    }
};

方法二:比较简洁

class Solution {
public:
    string multiply(string num1, string num2) {
        reverse(num1.begin(), num1.end());
        reverse(num2.begin(), num2.end());
        
        if (("0" == num1) || ("0" == num2)) {
            return "0";
        }
        
        string result = "";
        int i, j;
        int flag = 0, steps = 0;
        
        for (int i = 0; i < num1.length(); ++i) {
            int position = steps;
            
            for (int j = 0; j < num2.length(); ++j) {
                int v = (num1[i] - '0') * (num2[j] - '0') + flag;

                if (position < result.length()) {
                    v += result[position] - '0';
                    result[position] = (v % 10) + '0';
                }
                else {
                    result.append(1, (v % 10) + '0');
                }
                
                flag = v / 10;
                ++position;
            }
            
            if (flag > 0) {
                result.append(1, flag + '0');
            }
            
            flag = 0;
            ++steps;
        }
        
        reverse(result.begin(), result.end());
        
        return result;
    }
};




作者:hustyangju 发表于2015/3/27 16:07:14 原文链接
阅读:128 评论:0 查看评论

android开发之上传图片到七牛云存储服务器

$
0
0

相信很多开发者会把图片存放到七牛上,我的web站点也是吧图片存储到七牛上,对于以图片为主的站点,这样可以节省很大带宽。

将图片上传到七牛服务器的重点就是获得上传凭证uploadToken,直接把AccessKey和Secret放到客户端太不安全,容易被反编译。所以需要在服务器端根据AccessKey和Secret动态生成一个uploadToken,然后传回到客户端,客户端通过这个uploadToken将图片上传到七牛服务器。

第一、在服务器端生成uploadToken

//将图片上传到七牛 start
$bucket='七牛空间名称';
$expires = 3600;
$accessKey='去七牛查看';
$secretKey=<span style="font-family: Arial, Helvetica, sans-serif;">'去七牛查看';</span>
$client = new QiniuClient($accessKey,$secretKey);   
$flags = array();
$scope = $bucket;
$deadline = time() + $expires;
$flags['scope'] = $scope;
$flags['deadline'] = $deadline;
$flags['returnBody'] = null;
echo $client->uploadToken($flags);

这里注意一下bucket:七牛空间名称和deadline:uploadToken失效时间,具体可查看一下官网上传凭证介绍

uploadToken($flags)是自己封装的用于生成上传凭证的函数

<pre name="code" class="html"><span style="white-space:pre">	</span>public function uploadToken($flags)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>if(!isset($flags['deadline']))
<span style="white-space:pre">		</span>$flags['deadline'] = 3600 + time();
<span style="white-space:pre">		</span>$encodedFlags = self::urlsafe_base64_encode(json_encode($flags));
<span style="white-space:pre">		</span>$sign = hash_hmac('sha1', $encodedFlags, $this->secretKey, true);
<span style="white-space:pre">		</span>$encodedSign = self::urlsafe_base64_encode($sign);
<span style="white-space:pre">	</span>   <span style="white-space:pre">	</span>$token = $this->accessKey.':'.$encodedSign. ':' . $encodedFlags;
<span style="white-space:pre">	</span>    <span style="white-space:pre">	</span>return $token;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public static function urlsafe_base64_encode($str){
<span style="white-space:pre">	</span>    $find = array("+","/");
<span style="white-space:pre">	</span>    $replace = array("-", "_");
<span style="white-space:pre">	</span>    return str_replace($find, $replace, base64_encode($str));
<span style="white-space:pre">	</span>}


第二、下载qiniu-android-sdk-7.0.0.jarandroid-async-http-1.4.6并导入项目

第三、android上传图片

由于Android4.0 以后不允许在主线程进行网络连接,所以需要新开个线程来获取上传凭证。

<span style="white-space:pre">	</span>/*
	 * 上传图片到七牛
	 */
	private void uploadImg(){
		new Thread(new Runnable(){
			@Override
			public void run() {
				//获得七牛上传凭证uploadToken
				String token=getUploadToken();
				//手机SD卡图片存放路径
				String imgPath="";
				try {
					imgPath=FileUtil.getBasePath()+ "/test.jpg";
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(token!=null){
					String data = imgPath;
					//图片名称为当前日期+随机数生成
					String key = getRandomFileName();
					UploadManager uploadManager = new UploadManager();
					uploadManager.put(data, key, token,
					new UpCompletionHandler() {
						@Override
						public void complete(String arg0, ResponseInfo info, JSONObject response) {
							// TODO Auto-generated method stub
							Log.i("qiniu", info.toString());
						}
					}, null);
				}
				else{
					Log.i("fail", "上传失败");
				}
			}
		}).start();
	}

FileUtil.getBasePath()使用来获取SD卡基本路径,getRandomFileName()生成一个随机数来命名上传图片,具体方法我在这就不写了。

获得上传凭证的方法也很简单,直接使用httpget和服务器通信,获得第一步中生成的数据即可。(注意10.0.2.2是模拟器提供的特殊IP,等同于在电脑端的环回测试IP127.0.0.1)

	/*
	 * 获得七牛上传凭证uploadtoken
	 */

<span style="white-space:pre">	</span>private String getUploadToken()
<span style="white-space:pre">	</span>{
<span style="white-space:pre">	</span>    HttpClient client = new DefaultHttpClient();
<span style="white-space:pre">	</span>    StringBuilder builder = new StringBuilder();
<span style="white-space:pre">	</span> 
<span style="white-space:pre">	</span>    HttpGet myget = new HttpGet("http://10.0.0.2/test/getUploadToken.php");
<span style="white-space:pre">	</span>    try {
<span style="white-space:pre">	</span>        HttpResponse response = client.execute(myget);
<span style="white-space:pre">	</span>        BufferedReader reader = new BufferedReader(new InputStreamReader(
<span style="white-space:pre">	</span>        response.getEntity().getContent()));
<span style="white-space:pre">	</span>        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
<span style="white-space:pre">	</span>            builder.append(s);
<span style="white-space:pre">	</span>        }
<span style="white-space:pre">	</span>        return builder.toString();
<span style="white-space:pre">	</span>    } catch (Exception e) {
<span style="white-space:pre">	</span>        Log.i("url response", "false");
<span style="white-space:pre">	</span>        e.printStackTrace();
<span style="white-space:pre">	</span>        return null;
<span style="white-space:pre">	</span>    }
<span style="white-space:pre">	</span>}

通过LOG日志可以看到Qiniu--success,说明上传成功。





作者:tenderhearted 发表于2015/3/27 16:09:56 原文链接
阅读:104 评论:0 查看评论

开发记录笔记

$
0
0



自己攒了好多年好多技术解决方案.有用没用先留着,以后用


http://blog.sina.com.cn/passshang

作者:shangshang1029 发表于2015/3/27 16:13:43 原文链接
阅读:139 评论:0 查看评论

iOS获取ipa里的资源如图片等

$
0
0

iOS获取ipa里的资源如图片等

你可以自己在iphone上下载一个你想要的客户端,然后使用iTunes进行备份,把应用备份拷贝到本地后,把ipa的后缀名改为zip然后解压,在解压后的文件夹中找到.app右键显示包内容,在里面就可以拿到整个应用的素材。

作者:zz_mm 发表于2015/3/27 16:14:06 原文链接
阅读:129 评论:0 查看评论

指向同一个字符串的指针和数组的地址区别-包含const

$
0
0

1、代码如下:

#include<iostream> 
using namespace std;

int main()  
{
	char str1[]="abc";
	char str2[]="abc";
	const char str3[]="abc";
	const char str4[]="abc";
	const char *str5="abc";
	const char *str6="abc";
	char *str7="abc";
	char *str8="abc";

	cout<<(str1==str2)<<endl;
	cout<<(str3==str4)<<endl;
	cout<<(str5==str6)<<endl;
	cout<<(str7==str8)<<endl;
    return 0;  
}
2、输出结果如下:


3、分析:



因为str1-str4是申请了4个数组,所以他们的地址不同;而str5-str8是申请了4个指针,他们都指向同一个字符串,所以地址相同。
作者:a809146548 发表于2015/3/27 16:14:40 原文链接
阅读:135 评论:0 查看评论

单源最短路径问题——Dijkstra算法

$
0
0

解决单源最短路径问题的一般方法是Dijkstra算法,该算法是贪婪算法的典型应用。其基本思想是对有向赋权图以开始顶点出发,逐层外扩(即广度优先搜索),以寻找当前最短路径。
具体步骤以下图来说明:
1、从顶点V1为出发顶点,其距离dv1=0,为最小值,因此选择处理v1,将v1设为已知,与V1连接的顶点为v2、v4。其距离均小于当前dv4 和dv2的无穷大,因此更新:dv4=1,dv2=2;
2、选择当前距离最小未知顶点v4,,将v4设为已知。与v4邻接顶点为v3,v5,v6,v7,更新距离:dv3=1+2=3,dv6=1+8=9,dv7=1+4=5,dv5=1+2=3;(因为新值均小于他们的当前值无穷大,因此需要更新)。
3、选择当前距离最小未知顶点为v2,将v2设为已知。 与v2连接点为v4,但v4已知,因此不需更新。连接点v5,由于dv2+10=12>dv5=3,因此不更新dv5。
4、选择当前距离最小未知顶点v5,设为已知。更新其连接点:v7,但因为dv5+6=3+6> dv7=5,因此不用更新。
5、选择当前距离最小未知顶点v3,设为已知,且更新v6距离dv6=6。
6、最后选择v6,设为已知。此时所有顶点处理完毕。

实现代码如下:


/*Dijkstra 算法声明*/
typedef int Vertex;//顶点
typedef int DistType;
struct List;

/*每个顶点对应一个TaleEntry结构*/
struct TableEntry
{
 Lsit Header;//邻接顶点链表
 int Know;//表示该顶点是否已经已知(即处理过了)
 DistType Dist;//起点到该点的权值距离
 Vertex Path;//到达该点的前一顶点
};

/*顶点标号从0开始*/
#define NotAvertex (-1)
#define INF 0x7fffffff
typedef struct TableEntry Table[NumVertex];

/*表初始化*/
void InitTable(Vertex start,Graph G,Table T)
{
 int i; 
 ReadGraph(G,T);//将图读入到连接表中
 for(i=0;i<NumVertex;++i)
 {
  T[i].Know=false;
  T[i].Dist=INF;
  T[i].Path=NotAvertex;
 }
 T[start].Dist=0;
}

/*递归打印到给定顶点的最短路径*/
void PrintPath(Vertex V,Table T)
{
 if(T[V].Path!=NotAvertex)//如果还有前向顶点,则先打印前面的顶点
    {
     PrintPath(T[V].Path,T);
     printf(" to ");
    }
    printf(" %d ",V);
}

/*Dijkstra 算法*/
void Dijkstra(Table T)
{
 Vertex V,W;
 for(; ;)
 {
  V=smallest unknow distance vertex;//取当前未知顶点中的权值最小的顶点
  if(V==NotAvertex)
    break;

  T[V].know=true;
  for each W adjacent to V   //调整连接到V的所有顶点W的距离值
   if(!T[W].know)  //仅更新未知顶点
    {
        if(T[W].Dist>T[V].Dist+Cvw)//仅当新的距离值小于当前距离值时才更新它,并同时更新其前向节点
        {
         T[W].Dist=T[V].Dist+Cvw;
         T[w].Path=V;
        }
    }
 }

只要没有负值边,以上算法总能正确完成。
性能分析:
这里写图片描述
需要注意的是,如果用优先队列来实现查找最小距离时,每次将更新的dw要更新到原队列中对应点的d值,但是用二叉堆实现的优先队列的Find操作低效的。因此可以采取重复插入到优先队列的办法,这时队列中将可能存在一个点的多个版本,因此在每次DeleteMin操作把最小点从队列删除时,必须检查以肯定该点是未知的,从而避免对已知点重复处理,如果该点为已知,则丢弃,从新DeleteMin。这种实现方法不会增加时间界,但是会增加空间需求。当然可以选用其他的数据结构实现的优先队列,比如斐波那契堆等。

作者:yuyixinye 发表于2015/3/27 16:15:07 原文链接
阅读:95 评论:0 查看评论

解决android工程中如何运行java程序

$
0
0

在android工程中 默认运行配置的jar包为android.jar

如果不更改就不能运行 所以我们需要将android.jar改成java所需要的jre

 ① => Run Configurations

 ② =>  java application

 ③ => main

 ④ => classpath

 ⑤ => 删除android.jar

 ⑥ => advanced

 ⑦ => Add Library

 ⑧ => JRE System Library

 ⑨ => finish/run

作者:violetIC 发表于2015/3/27 16:16:40 原文链接
阅读:152 评论:0 查看评论

maven package编译打包jar出错解决

$
0
0

只需要在pom中加入如下插件:

<plugin>  

            <artifactId>maven-compiler-plugin</artifactId>  
            <version>2.3.2</version>  
            <configuration>  
                <source>1.6</source>  
                <target>1.6</target>  
                <encoding>UTF-8</encoding>  

            </configuration>  

</plugin>  


  1. <version>2.3.2</version>  
这个版本是必须要指定

作者:zhanjianshinian 发表于2015/3/27 16:17:26 原文链接
阅读:126 评论:0 查看评论

boost::smart_ptr之智能指针

$
0
0

前言:


1.scoped_ptr 智能指针使用说明

示例代码:

#include "stdafx.h"
#include <boost/smart_ptr.hpp>
#include <iostream>

using namespace std;
using namespace boost;

class posix_file
{
public:
	posix_file(const char *  file_name)
	{
		cout << "open file!   " << *file_name << endl;
 	}
	~posix_file()
	{
		cout << "close file!" << endl;
	}
};

int main(int argc, _TCHAR* argv[])
{
	/************************************************************************/
	/*scoped_ptr不允许赋值,拷贝,不支持--和++,只能在被声明的作用域内使用  */
	/************************************************************************/
	scoped_ptr<string> sptr(new string("test"));
	cout <<  "指针内容为:" << (*sptr).c_str()  << endl;
	cout <<  "指针内容长度为:" << sptr->size()  << endl;
	scoped_ptr<int> iptr (new int);
	*iptr = 1000;
	cout << *iptr << endl;
	{
		scoped_ptr<posix_file> fptr(new posix_file("/file/filename"));
	}

	while (1);
	return 0;
}
运行结果:


作者:qingzai_ 发表于2015/3/27 16:17:45 原文链接
阅读:91 评论:0 查看评论

C++中Lambda表达式

$
0
0

C++11中也支持Lambda表达式了,即匿名函数。

首先看一个例子,对Lambda表达式有一个感性的认识:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int count = 10;
    vector<int> nums(count, 1);
    int x = 1, y = 1;
    //generate_n 函数调用中的lambda表达式将vector对象中的一个元素赋值为其前两个元素的和
    generate_n(nums.begin() + 2, count - 2, [=]() mutable -> int {
        int n = x + y;
        x = y;
        y = n;
        return n;
    });
    //for_each输出vector对象中的元素
    for_each(nums.begin(), nums.end(), [](int num) {
        cout << num << ' ';
    });
    cout << endl;
    return 0;
}

结果如下:
实验结果


C++中Lambda表达式语法如下:

Lambda表达式
其中,

  1. lambda-introducer (称为捕获子句)

  2. lambda-parameter-declaration-list (称为参数列表)

  3. mutable-specification (称为可变声明)

  4. exception-specification (称为异常声明)

  5. lambda-return-type-clause (称为返回类型)

  6. compound-statement (称为lambda主体)

lambda introducer
[lambda-introducer],标识一个Lambda表达式的开始,这部分必须存在,不能省略。lambda-introducer中的参数是传递给编译器自动生成的函数对象类的构造函数的。函数对象参数只能使用那些到定义Lambda为止时Lambda所在作用范围内可见的局部变量(包括Lambda所在类的this)。函数对象参数有以下形式:
1、[]:不使用任何对象参数。
2、[=]:函数体内可以使用Lambda所在作用范围内所有可见的局部变量(包括Lambda所在类的this),并且是值传递方式(相当于编译器自动为我们按值传递了所有局部变量)。
3、[&]:函数体内可以使用Lambda所在作用范围内所有可见的局部变量(包括Lambda所在类的this),并且是引用传递方式(相当于编译器自动为我们按引用传递了所有局部变量)。
4、[this]:函数体内可以使用Lambda所在类中的成员变量。
5、[a]:将a按值进行传递。按值进行传递时,函数体内不能修改传递进来的a的拷贝,因为默认情况下函数是const的。要修改传递进来的a的拷贝,可以添加mutable修饰符。
6、[&a]:将a按引用进行传递。
7、[a, &b]:将a按值进行传递,b按引用进行传递。
8、[=,&a, &b]:除a和b按引用进行传递外,其他参数都按值进行传递。
9、[&, a, b]:除a和b按值进行传递外,其他参数都按引用进行传递。

参数列表(如果没有可以省略)
参数列表和普通函数参数列表一样,使用()括起来。参数可以通过按值(如(a,b))和按引用(如(&a,&b))两种方式进行传递。没有参数时,参数列表可以省略。

mutable和exception声明(可选的)
mutable或exception声明,这部分可以省略。按值传递函数对象参数时,加上mutable修饰符后,可以修改按值传递进来的拷贝(注意是能修改拷贝,而不是值本身)。exception声明用于指定函数抛出的异常,如抛出整数类型的异常,可以使用throw(int)。

返回类型
->返回值类型,标识函数返回值的类型,当返回值为void,或者函数体中只有一处return的地方(此时编译器可以自动推断出返回值类型)时,这部分可以省略。

lambda主体
{函数体},标识函数的实现,这部分不能省略,但函数体可以为空。

作者:T_27080901 发表于2015/3/27 16:19:11 原文链接
阅读:121 评论:0 查看评论

Android Activity 平滑水平切换动画

$
0
0

在Android当中 设置activity的动画 需要复写 android:windowAnimationStyle这个属性

我们自定义一个动画样式来继承 @android:style/Animation(Base style for animations.  This style specifies no animations)这个样式是Android操作系统提供的 没用动画的样式 我们定义其中的4个属性还设置我们想要的效果

android:activityOpenEnterAnimation 一个activity创建进入的效果

android:activityOpenExitAnimation 一个activity还没有finish()下退出效果, 比如有俩个activity A,B 首先启动A 然后再启动B 那么A还没有finish() 这A的退出效果

android:activityCloseEnterAnimation 表示上一个activity返回进入效果 比如有俩个activity A,B B退出后A进入的效果

activityCloseExitAnimation 表示的是activity finish()之后的效果 比如有俩个activity A,B B退出后会被finish() 那么B的退出效果在这定义

下面给出程序中需要用到的主题:

<!--动画左右切换的theme-->
    <style name="LeftRight" parent="@android:style/Theme.Translucent.NoTitleBar">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowAnimationStyle">@style/AnimationActivity</item>
    </style>
       <!--
       1:第一个表示新的activity创建进入效果
       2:第2个表示activity还没有finish()下退出效果
       3:第3个表示上一个activity返回进入效果
       4:第4个表示的是activity finish()之后退出效果
       -->
    <style name="AnimationActivity" mce_bogus="1" parent="@android:style/Animation.Activity">
        <item name="android:activityOpenEnterAnimation">@anim/in_from_right</item>
        <item name="android:activityOpenExitAnimation">@anim/out_to_left</item>
        <item name="android:activityCloseEnterAnimation">@anim/in_from_left</item>
        <item name="android:activityCloseExitAnimation">@anim/out_to_right</item>
    </style>

下面给出4个动画文件:

1:in_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p"
               android:toXDelta="0%p"
               android:duration="500"/>
</set>

2:in_from_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p"
               android:toXDelta="0%p"
               android:duration="500"/>
</set>

3:out_from_right

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0%p"
               android:toXDelta="100%p"
               android:duration="500"/>
</set>

4:out_from_left

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0%p"
               android:toXDelta="-100%p"
               android:duration="500"/>
</set>

最后给出相应AndroidManifast文件中是如何配置的:

<activity
                android:name="xxxx"
                android:configChanges="keyboardHidden|orientation|screenSize"
                android:screenOrientation="portrait"
                android:theme="@style/LeftRight"
                android:windowSoftInputMode="adjustPan|stateHidden">
        </activity>

自己使用的时候发现的问题:刚开始的时候动画写好以后,运行程序发现动画时有时无,不知道什么原因,但是在其他Activity上面验证是好的,我了个擦,后来发现我在那个有问题的Activity中复写了父类的onWindowFouceChanged方法,在里面计算了某个View距离顶部的距离,最后将这部分代码拿出来,放到其他地方进行计算,动画就好了,坑爹啊!

在这个把这个问题记录一下~

作者:ly985557461 发表于2015/3/27 16:20:10 原文链接
阅读:129 评论:0 查看评论

字典树 ,map 容器 hdu 1251

$
0
0

统计难题

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 20471    Accepted Submission(s): 8907


Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
 

Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 

Sample Input
banana band bee absolute acm ba b band abc
 

Sample Output
2 3 1 0
 

Author
Ignatius.L

//考查知识点:map容器 
#include<stdio.h>
#include<string.h>
#include<string>
#include<map>
using namespace std;
int main()
{
	char s[12];
	char a[12];
	map<string,int>m;
	while(gets(s))
	{
		int len=strlen(s);
		if(!len)
		break;
		int i;
		for(i=len;i>=1;--i)
		{
			s[i]='\0';
			m[s]++;
		}
	}
	while(gets(a))
	{
		printf("%d\n",m[a]);
	}
	return 0;
} 
法二:字典树 模板 
//考查知识点:字典树 我终于也要努力了 ,加油 要真正的做自己。。。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct s{
	struct s *child[28];
	int n;
}node,*Node;
Node root;
void insert(char *s)
{
	Node current=NULL;
	Node newnode=NULL;
	current=root;
	int len=strlen(s),i,j,now;
	for(i=0;i<len;++i)
	{
		now=s[i]-'a';
		if(current->child[now]!=NULL)
		{
			current=current->child[now];
			(current->n)++;
		}
		else
		{
			newnode=(Node )calloc(1,sizeof(node));//没有改字母 先声明一个 内存空间  
			current->child[now]=newnode;//将此空间的首席之分配给该字母 
			current=newnode;// 
			current->n=1;
		}
	}
}
int find(char *s)
{
	int i,j,len=strlen(s),now;
	Node current=NULL;//初始化 
	current=root;
	for(i=0;i<len;++i)
	{
		now=s[i]-'a';
		if(current->child[now]!=NULL)//该遍历的字符串存在对应的那个字母 
		{
			current=current->child[now];
		}
		else//不匹配直接退出  
		return 0;
	}
	return current->n;
}
int main()
{
	char a[100010],temp[100010];
	root=(Node)calloc(1,sizeof(node));
	while(gets(a),strcmp(a,""))
	{
		insert(a);
	}
	while(gets(temp))
	{
		printf("%d\n",find(temp));
	}
	return 0;
} 



作者:Ice_Alone 发表于2015/3/27 16:21:16 原文链接
阅读:100 评论:0 查看评论

unity纹理总结

$
0
0

转载请注明出处

我们知道手游的表现力和美术密不可分,美术资源的滥用往往会导致大量的美术返工。所以根据游戏的需要制定合理的美术规格十分重要的。写这篇文章的目的在于解决两个问题。第一,美术作图有怎么样的规范,第二,图片unity怎么处理最好。

因为我们项目是2D项目,很少涉及3D模型,我们这里的美术资源就特指2D Texture。

特别的,我们在这里只研究texture type为sprite 的情况。因为场景中的object的component只有sprite render,而且这样也覆盖了gui。

 

首先介绍一下sprite的各个参数的简单含义。

Sprite Mode: single独立图片multiple  多张有关联图片,可以editor切割

Packing tag:  同样的tag可以在sprite packer中打包图集,pro only

Pixelstounit:  单元sprite像素数量,越大越精细,默认100

Pivot:       中心点,设计到rotate的时候特别要当心

Mipmaps:   多重纹理,内存多1/3。做3D的话建议详细了解一下

Fitermode:  被拉伸时候的填充模式

Maxsize:    图片大小

Format:     纹理格式

 

详情参见http://docs.unity3d.com/Manual/class-TextureImporter.html

 

与纹理相关的几个方面:内存大小,安装包大小和drawcall。当然还有cpu,gpu处理速度,读取速度,这里就不讨论了,我们专心讨论以上三点。

 

首先讨论内存和安装包:

 

Unity资源选中图片,inspector显示的大小,即读入内存的大小。我们知道,unity可以读取多种图片格式,它内部会处理成为自己的专门格式,打包的时候会以assetbundle方式存放。所以,内存的大小依赖于纹理参数,而与图片是什么格式的没有关系的。而打包成为assetbudle和内存相关同时也和原图的大小相关。(其实取决于原图大小和纹理参数)。我们可以简单地认为内存占用多了,安装包就大。

我们首先来看一下psd图片直接放在unity的情况。(maxsize= 1024  format = truecolor)


再看一下maxsize,format对内存及安装包的影响。


上面两份表格中1024*1024分辨率的用的是同样的图片。我们可以看出,IOS上可以压缩(POT图,正方形图)对内存和包大小有很大的优化,而format和maxsize同样也有影响。

 

抛开实验图片不谈,针对我们的游戏(大量透明图,色彩数广)对原图(大于1024*1024)的不同处理会有不同的效果:

1 maxsize调整为512。稍微失真,可以接受。

2 format由RGBA32调整为 RGBA16。完全失真,不能接受。

3 IOS压缩为PVRTC4bit。失真非常小,完全可以接受。

4安卓压缩为RGBA16。完全失真,不能接受。

 

再看一份表格,同样的图片表现,美术在作图时处理为不同分辨率。


其中1024*1024的图片内存直接从4M到0.5M,安装包减少4倍。优势实在太明显了,遗憾的是,它只支持IOS,安卓却不可以。

 

再次我们讨论drawcall

对于纹理首先想到的就是纹理合并。对于spritepacker,官方文档中“For optimal performance”主要有两点,即对于empty space和 drawcall的影响。于是对于drawcall的讨论我们这里变成对spritepacker的讨论

详情参见http://docs.unity3d.com/Manual/SpritePacker.html

 

Sprite render同一材质不同纹理依旧会产生多个drawcall,而纹理的合并会减少drawcall。实际上在我们的游戏中,摄像机范围内的图片总是有限的,drawcall的数量很低的,所以我们的重点不在这里,而是spritepacker对空间的影响。

         如果我们对场景中大图小图全图打包会如何,场景加载时候无论用到什么图,都会载入图集的内存,如果只用到了小图,那么图集的出场无异于牛刀杀鸡,这也是为什么好多项目谈经验的时候只对GUI的图进行图集处理,并不是NGUI做了这份工作,以前没有UGUI的时候没做。

         而我们的场景中基本都是背景图,所以并不适合打包进图集,而小的“零件图片”却可以被pack,多余的加载可以换来IO的节省,这样的规划应该是比较合理的。

         关于spritepacker其实还有个问题没有研究清楚。Pack后的图集是放在library的cache里面的,library添加到SVN的ignore里面的。按照官方说法,如果cache没有图集,则会再次pack。可是我们知道,pack的时候可以定制的。改变pack方式难道不保存在一个setting文件里面传上去吗?还是在library文件里面被ignore掉了。前面我在思考这样一个问题:

如果美术给的图是NPOT的多张RGBA32图,打包到了一个1024*1024的图中,选择的是定制的spritepacker,设置图集的entry.settings.format = TextureFormat.PVRTC_RGBA4,是否意味着我对这10张都进行了合并成一个RGBA32格式的图集然后进行对图集PVRTC压缩?如果是这样的话,那么不就是可以进一步优化了?不过话说回来,小图的表现力就那么微观,稍微一点失真还是可以看出来的,另一方面优化的程度也没有那么大,整个等项目后期处理时候再考虑吧。

 

总结上面,针对我们项目的处理方案:

美术作图:Height/width 256以下图片任意作图,因为好多与UI类似。

Unity处理:选择RGBA32做spritepacker,是否可以压缩为PVRTC再做考量。

美术作图:Height/width 256+的图片,做成POT图片

Unity处理:2048/1024的maxsize设置为1024/512(失真可接受),PVRTC压缩。

 

上面主要考虑的是IOS的情况。如果安卓的话先留两个思路吧。第一个 “目前主流的Android机型基本都支持ETC1格式压缩。但ETC1只能支持非Alpha通道的图片压缩。所以一般把Alpha通道图分离出来,绘制到GPU显存时,a值从Alpha图里获取,无Alpha通道的图就可以使用ETC1压缩。”第二点依旧从maxsize做处理。以上的讨论和总结都是针对我们自己的项目而言。不同项目应该有不同关注点,具体参数的理解还是要再看看文档和经验。希望文章能帮助到有需要的同学,不对之处希望给予指正。
作者:abeyondc 发表于2015/3/27 16:22:55 原文链接
阅读:106 评论:1 查看评论

地图-大头针视图

$
0
0
//
//  MKMapViewController.m
//  MKMapView
//
//  Created by xiaoyao on 15/3/25.
//  Copyright (c) 2015年 lije. All rights reserved.
//

#import "MKMapViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "CAnnotation.h"

@interface MKMapViewController ()<MKMapViewDelegate,CLLocationManagerDelegate> {
  MKMapView *_mapView;
  CLLocationManager *_locationManager;
}
@end

@implementation MKMapViewController

- (void)viewDidLoad {
  [super viewDidLoad] ;
  
  [self setUpUI];
}

- (void)setUpUI {
  CGRect rect = [UIScreen mainScreen].bounds;
  _mapView = [[MKMapView alloc] initWithFrame:rect];
  _mapView.delegate = self;
  [self.view addSubview:_mapView];
  
  if (![CLLocationManager locationServicesEnabled] ||
      ![CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
    [_locationManager requestWhenInUseAuthorization];
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
  }
  
  // 设置
  _mapView.mapType = MKMapTypeStandard;
  // 返回用户追踪轨迹,启动定位
  _mapView.userTrackingMode = MKUserTrackingModeFollow;
  
  CAnnotation *ca = [[CAnnotation alloc] init];
  CLLocationCoordinate2D coor = CLLocationCoordinate2DMake(36.56, 101.74);
  ca.title = @"lije";
  ca.subtitle = @"lije’home";
  ca.coordinate = coor;
  ca.image = [UIImage imageNamed:@"ca1"];
  // 添加大头针
  [_mapView addAnnotation:ca];
  
  CAnnotation *ca2 = [[CAnnotation alloc] init];
  CLLocationCoordinate2D coor2 = CLLocationCoordinate2DMake(41.31, 121.51);
  ca2.title = @"zs";
  ca2.subtitle = @"zs’home is jinzhou";
  ca2.coordinate = coor2;
  ca2.image= [UIImage imageNamed:@"ca2"];
  [_mapView addAnnotation:ca2];
}
#pragma mark - 地图代理方法
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
  NSLog(@"%@",userLocation);
}

// 返回大头针视图
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
  if ([annotation isKindOfClass:[CAnnotation class]]) {
    static NSString *anotationKey = @"Annotation1";
    MKAnnotationView *annotationView = [_mapView dequeueReusableAnnotationViewWithIdentifier:anotationKey];
    // 如果缓冲池不存在则创建缓冲池对象
    if (!annotationView) {
      annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:anotationKey];
      annotationView.canShowCallout = true;
      UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zs.jpeg"]];
      annotationView.leftCalloutAccessoryView = imageView;
      annotationView.calloutOffset = CGPointMake(0, 1);
    }
    
    annotationView.annotation = annotation;
    annotationView.image = ((CAnnotation *)annotation).image;
    return annotationView;
  } else {
    
    // 如果返回nil则使用默认的大头针视图
    return nil;
  }
}
@end
//
//  CAnnotation.h
//  MKMapView
//
//  Created by xiaoyao on 15/3/25.
//  Copyright (c) 2015年 lije. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface CAnnotation : NSObject<MKAnnotation>

/**
 *  @brief 定制大头针,重写大头针协议的三个属性
 */
@property (nonatomic, copy)   NSString *title;  // 大头针标题

@property (nonatomic, copy)   NSString *subtitle; // 副标题

@property (nonatomic) CLLocationCoordinate2D coordinate; // 位置

// 自定义大头针图片属性
@property (nonatomic, strong) UIImage *image;

@end

作者:u010606986 发表于2015/3/27 16:23:45 原文链接
阅读:89 评论:0 查看评论
Viewing all 35570 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>