三种算法求最大子段和问题——Java实现
给定由n个整数组成的序列(a1, a2, …, an),求该序列的子段和的最大值,当所有整数均为负整数时,其最大子段和为0。
LargestSubsegmentSum1.java //蛮力算法
import java.util.*;
public class LargestSubsegmentSum1
{
public static void main(String[] args)
{
/**
*从键盘输入所要求的序列的长度n
*/
Scanner in=new Scanner(System.in);
System.out.println("Please enter the length of segment you want to make(输入你要求的序列的长度):");
int n=in.nextInt();
/**
*从键盘输入所要求的序列,存储在a[n]中
*/
int[] a=new int[n];
System.out.println("Now,please enter the elements of the segment you want(现在请依次输入这个序列包含的元素(整数)):");
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
}
double startTime=System.currentTimeMillis();//starttime
/**
*求解最大子段和存在maxSum中
*/
int maxSum=a[0];
for(int i=0;i<n-1;i++)
{
int temp=a[i];
for(int j=i+1;j<n;j++)
{
temp+=a[j];
if(temp>maxSum)
maxSum=temp;
}
}
double endTime=System.currentTimeMillis();//endtime
/**
*打印输出求解结果和程序所用时间
*/
System.out.println("The largest sub-segment sum is(最大子段和是):"+maxSum);
System.out.println("Basic Statements take(基本语句用时) "+(endTime-startTime)+" milliseconds!");
}
}
****************************
相关文档:
1. 一个java源文件只有一个public类且类名与文件名一致。注:一个可运行的java应用程序应有一个main方法,且格式固定,但不一定在public类中。
2. package语句只能有一个且放在程序的第一行。
3. 整数在内存中式按照其补码来存储的,正数的补码=原码,负数的补码=原码取反加1 ,char无符号位(0~65535)
4. 强制 ......
来源:http://cj1240.zhmy.com/archives/2008/148832.html
JAVA 中的IO流
一、流的概念
流(stream)的概念源于UNIX中管道(pipe)的概念。在UNIX中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备、外部文件等。
&nb ......
最初Java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中write(char[] ch,int off,int length),flush()和close()方法为抽象方法,Reader中read(char[] ch,int off,int length)和close()方法是抽象方法。子类应该分别实现他们。
当我们读写文 ......
设p1=(x1, y1), p2=(x2, y2), …, pn=(xn, yn)是平面上n个点构成的集合S,设计算法找出集合S中距离最近的点对。
蛮力算法描述:
int ClosestPoints(int n, int x[ ], int y[ ], int &index1, int &index2)
{
minDist=+∞;
for (i=1; i<n; i++)
&n ......
try{
URL url=new URL("http://baidu.com");
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
String s="";
StringBuffer sb=new StringBuffer("");
while((s=br.readLine())!=null) {   ......