1.magic coupon
有一些小细节有错,不想改了。
如果用i和j分别操作数组就不会出错。
#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main(){
int n,m;
int cou[100],pro[100];
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&cou[i]);
}
sort(cou,cou+n,cmp);
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%d",&pro[i]);
}
sort(pro,pro+m,cmp);
int sum=0;
for(int i=0;i<n;i++){
if(cou[i]<0||pro[i]<0){
break;
}else{
sum+=cou[i]*pro[i];
printf("%d ",cou[i]*pro[i]);
}
}
while(1){
if(cou[n-1]>0||pro[m-1]>0){
break;
}else{
sum+=cou[n-1]*pro[m-1];
printf("%d %d\n",cou[n-1],pro[m-1]);
n--;
m--;
}
}
printf("%d\n",sum);
return 0;
}
2.sort with swap 0
我一开始是用数组的坐标存位置,数组的值存数值,但是这样到后面就没用了
得和书里一样,用坐标存值,用值存位置,所以又是一个错误代码
#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;
int main(){
int n;
scanf("%d",&n);
int martix[100],now,pos,num=0;
for(int i=0;i<n;i++){
scanf("%d",now);
martix[i] = now;
if(now ==0 ){
pos = i;/0的位置
}
if(now!=i&&now1=0){
num++;//移动次数
}
}
int times=0,wrong=1;
while(num>0){
if(martix[0]==0){
while(wrong<n){
if(martix[wrong]!=wrong){
swap(martix[0],martix[wrong]);
pos = wrong;
times++;
break;
}
wrong++;
}
}
while(martix[0]!=0){
swap(martix[pos],martix[])
}
}
return 0;
}
3.recover the smallest number
这里用到了string,大部分都在copy了
#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
bool cmp(string a, string b){
return a+b<b+a;
}
int main(){
string str[1010];
int n;
cin >> n;
for(int i=0;i<n;i++){
cin>>str[i];
}
sort(str,str+n,cmp);
string ans;
for(int i=0;i<n;i++){
ans+=str[i];
}
while(ans.size()!=0&&ans[0]=='0'){
ans.erase(ans.begin());
}
if(ans.size()==0){
cout <<0;
}else{
cout <<ans;
}
return 0;
}