class max_asc_seq implements I_algorithm {
/**
* 问题:寻找最长的单调递增子序列 思路:用b[j]表示以第j个数到最后一个数的最长单调递增子序列,再从后向前遍历,查找试b[j]最大的值
* */
private int[] data;
private int length;
private int[] result;
int[] temp;
double time;
public max_asc_seq() {
}
@Override
public void Init() {
length = 100;
data = new int[length];
}
@Override
public void CreateData() {
Random r = new Random();
for (int j = 0; j < this.length; j++)
data[j] = r.nextInt(this.length);
// int[]a={1,17,14,6,76,4,58,34,86,2,46,92,96,93,28,95,99,64,68,34};
// data=a;
}
@Override
public void RunAlgorithm() {
long base=System.currentTimeMillis();
temp= new int[this.length];
int maxat = this.length - 1;
for (int j = 0; j < this.length; j++)
temp[j] = 1;
for (int j = this.length - 2; j >= 0; j--) {
for (int k = this.length - 1; k > j; k--)
if (data[k] > data[j] && temp[k] + 1 > temp[j])
temp[j] = temp[k] + 1;
if (temp[j] >= temp[maxat]) {
maxat = j;
}
}
this.result = new int[temp[maxat]];
this.result[0] = this.data[maxat];
int next = 1;
next = 1;
for (int k = maxat + 1; k < this.length; k++)
if (data[k] > data[maxat] && temp[k] + 1 == temp[maxat]) {
this.result[next++] = this.data[k];
maxat = k;
}
this.time=(System.currentTimeMillis()-base)/1000.0;
}
@Override
public boolean IsRunCorrect() {
return true;
}
@Override
public void ShowResult() {
System.out.println("给定序列:");
showInts(this.data);
System.out.println("最长递增子序列序列:");
this.showInts(this.result);
System.out.println("运行时间:"+time);
// System.out.println("temp:");
// this.showInts(temp);
}
private void showInts(int[]a) {
for (int k = 0; k < a.length / 10; k++) {
for (int j = 0; j < 9; j++)
System.out.print(String.format("%4s", a[k * 10 + j] + ","));
System.out.println(a[k * 10 + 9]);
}
if (a.length % 10 != 0) {
for (int k = a.length / 10 * 10; k < a.length - 1; k++)
System.out.print(String.format("%4s", a[k ] + ","));
System.out.println(String.format("%4s", a[a.length-1]+"" ));
}
}
@Override
public void ShowOriginalData() {
System.out.println("给定序列:");
for (int j = 0; j < this.length - 1; j++)
System.out.print(data[j] + ",");
System.out.println(data[length - 1]);
}
}
寻找最长递增子序列
最新推荐文章于 2020-02-15 23:25:02 发布