C++ code - Bài toán chia tài sản Nhập môn trí tuệ nhân tạo
//Bai toan chia tai san //@author Hoaibang #include<iostream> #include<stdio.h> using std::cin; using std::cout; void nhapTaiSan(int a[], int &n); void inMang(int a[], const int &n); void selectionSort(int a[], const int &n); void chiaTaiSan(int a[], const int &n, int a1[], int &n1, int a2[], int &n2); int tongTS1=0, tongTS2=0; int main(void){ int a[20], a1[10], a2[10], n=0, n1=0, n2=0; nhapTaiSan(a,n); inMang(a,n); selectionSort(a,n); inMang(a,n); chiaTaiSan(a,n,a1,n1,a2,n2); inMang(a1,n1); inMang(a2,n2); getchar(); return 0; } void nhapTaiSan(int a[], int &n){ cout<<"Nhap so luong tai san: "; cin>>n; for(int i=0;i<n;i++){ cout<<"a["<<i<<"]= "; cin>>a[i]; } } void inMang(int a[], const int &n){ cout<<"\n"; for(int i=0;i<n;i++){ cout<<a[i]<<" "; } } void selectionSort(int a[], const int &n){ for(int i=0;i<n-1;i++){ int iMax=i; for(int j=i+1;j<n;j++){ if(a[j]>a[iMax]){ iMax=j; } } int temp=a[i]; a[i]=a[iMax]; a[iMax]=temp; } } void chiaTaiSan(int a[], const int &n, int a1[], int &n1, int a2[], int &n2){ int tongTS=0; for(int i=0;i<n;i++){ tongTS=tongTS+a[i]; } int nuaTongTS=tongTS/2; a1[0]=a[0]; n1=1; tongTS1=a1[0]; for(int i=1;i<n;i++){ if(tongTS1+a[i]<=nuaTongTS){ a1[n1++]=a[i]; tongTS1=tongTS1+a[i]; } else{ a2[n2++]=a[i]; tongTS2=tongTS2+a[i]; } } }
0 nhận xét:
Đăng nhận xét