Skip navigation.

TÌM DÃY CON TĂNG DÀI NHẤT

1/ Tìm dãy con tăng dài nhất trong mảng một chiều.
2/ Xuất dãy con tăng đó ra.

//M-CONTAN.CPP
//--Ky thuat lap trinh voi mang mot chieu
//--Nguyen Van Don
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#define max 50
//-------------------------------------------
void nhap(int a[max],int &n);
void xuat(int a[max],int n);
void mangcontang(int a[max],int n);
//--------------------------------------------
void nhap(int a[max],int &n)
{
randomize();
cout<<"\n Nhap so phan tu cua mang: ";
cin>>n;
for(int i=0;i<n;i++)
a=random(20);
}
void xuat(int a[max],int n)
{
for(int i=0;i<n;i++)
cout<<"\t"<<a;
}

void mangcontang(int a[max],int n)
{
int d=0;//luu vi tri dau cua day con
int c=0;//Luu vi tri cuoi cua day con
int temp=0;//Bien tam luu do dai cua day con

for(int i=0;i<n-1;i++)
{
int dem=0;
int j=i;
while(a[j]<=a[j+1]&&j<n)
{
dem++;
j++;
}
if(dem>temp)
{
temp=dem;
d=i;
c=j;
}
}
cout<<"\n Mang con tang dai nhat";
cout<<endl;
for(int h=d;h<=c;h++) //xuat day con dai nhat
{
cout<<"\t"<<a[h];
}

}
//----------------------------------------
void main()
{
clrscr();
int a[max],n;
nhap(a,n);
xuat(a,n);
mangcontang(a,n);
getch();
}

THƠ CON CÓC TÌM SỐ LẺ TRONG MẢNG LÀ BỘI CỦA 3,5,7

Comments

Anonymous 1. October 2009, 03:52

Lonely writes:

thuat toan ko chay dung khi gan n=10 mang a={2,6,-7,5,8,1,-3,5,15,9}
de nghi ban coi lai

Nguyễn Văn Đôn 2. October 2009, 10:41

Mình đã thử lại trường hợp n=10 như của bạn rồi nhưng thuật toán chạy vẫn đúng mà.
Output sẽ là: -7,5,8
Đây là dãy con có giá trị tăng dần dài nhất của mảng một chiều này.
-3,5,15 cũng là dãy con tăng dài bằng -7,5,8 nhưng sẽ lấy dãy đầu tiên là -7,5,8.

How to use Quote function:

  1. Select some text
  2. Click on the Quote link

Write a comment

Comment
(BBcode and HTML is turned off for anonymous user comments.)

If you can't read the words, press the small reload icon.


Smilies