算法基础上机实验——2023年5月8日

1.

#include<bits/stdc++.h>
using namespace std;
int n, a[1005];
int main(){
    cin >> n;
    for(int i = 1; i <= n; i ++)
        cin >> a[i];
    sort(a + 1, a + 1 + n);
    for(int i = n; i > 1; i --)
            cout << a[i] << ' ';
    cout << a[1] << endl;
    return 0; 
}

2.

#include<iostream>
using namespace std;
int a[6],b[100];
int main(){
	int maxn=-1;
	for(int i=1;i<=6;i++){
		cin>>a[i];
	}
	b[1]=a[1];
	for(int i=2;i<=6;i++){
		b[i]=max(a[i],a[i]+b[i-1]);
		if(b[i]>maxn){
			maxn=b[i];
		}
	}
	for(int i=1;i<=6;i++){
		cout<<a[i]<<" ";
		
	}
	cout<<endl;
	cout<<"数组a的最大连续子段和为:"<<maxn;
	return 0; 
} 

3.

void Merge(int r[ ], int s, int m, int t)  
{
    int r1[t], i = s, j = m + 1, k = s;
    while (i <= m && j <= t)
    {   
        if (r[i] <= r[j])  r1[k ++] = r[i ++];        //较小者放入r1[k]
        else r1[k++] = r[j++]; 
    }
    while (i <= m)                                        //处理第一个子序列剩余记录
         r1[k ++] = r[i ++];
    while (j <= t)                                          //处理第二个子序列剩余记录
         r1[k ++] = r[j ++];   
    for (i = s; i <= t; i++)                             //将合并结果传回数组r
        r[i] = r1[i];
}

01背包问题

#include <iostream>

using namespace std;

const int N = 1010;

int n, m;
int v[N], w[N];
int f[N];

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i ++) cin >> v[i] >> w[i];
    for (int i = 1; i <= n; i ++)
        for (int j = m; j >= v[i]; j --)
            f[j] = max(f[j], f[j - v[i]] + w[i]);
    cout << f[m] << endl;
    
    return 0;
}
posted on 2023-05-08 18:24  逆袭怪  阅读(20)  评论(0编辑  收藏  举报