第四章实践

第四章印象比较深的是以下几个问题:

1,最优合并

最优合并问题最深刻的就是“sort(a,a+n);”这一句。一开始我队写的是“sort(a+u+1,a+n);”。按理论上来说,如果整段代码都这样的话是要出问题的,但是只有求最坏的情况的时候才会出问题。巧的是我们求最坏的情况的时候不用a了,用的是b,也就是“sort(b,b+n);”,代码也同求最优情况的时候不一样了,不加上u+1,所以就侥幸过了。以下代码:

#include <iostream>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
int n;
cin>>n;
int a[n];
int b[n];
for(int u=0;u<n;u++)
{
cin>>a[u];
}
sort(a,a+n);
for(int k=0;k<n;k++)
{
b[k] =a[k];
}
int good =0;
for(int u=0;u<n;u++)
{
if(u==(n-1))
break;
good = (good + a[u] + a[u+1]-1);
a[u+1] = a[u]+a[u+1];
sort(a,a+n);
}
int bad =0;
for(int u=n-1;u>0;u--)
{
bad = (bad + b[u] + b[u-1]-1);
b[u-1] = b[u]+b[u-1];
sort(b,b+u);
}
cout<<bad<<" ";
cout<<good;

return 0;
}

2,删数问题没什么讲的,除了后来想到了第一个数可能为0,比如说输入“10213    3”,那么输出就不应该是“01”,而应该直接就是“1”。没什么说的,直接上代码。

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
char s[150];
int n;
cin>>s;
cin>>n;
while(n > 0){
int len = strlen(s);
int i =0;
while(i < len && s[i] <= s[i+1]){
i++;
}
while(i < len){
s[i] = s[i+1];
i++;
}
n--;
}
int k;
while(s[0] == '0'){
k = 0;
int len = strlen(s);
while(k < len){
s[k] = s[k+1];
k++;
}
}
cout<<s;
return 0;
}

3,存储问题就比较简(ruo)单(zhi)了,直接排列后一个个放进去完事。

#include<iostream>
#include<algorithm>
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
int n;
int len;
cin>>n;
cin>>len;
int a[n];
for (int i=0;i<n;i++)
{
cin>>a[i];
}

sort(a,a+n);

int sum=0;
int i=0;
for(i;i<n;i++)
{
sum = sum + a[i];
if(sum>len)
{
break;
}
}
cout<<i;
return 0;
}

 

posted on 2018-12-03 21:06  吕涵宇  阅读(66)  评论(0编辑  收藏  举报