解题思路:
1.排序
2.还记得快排吗!用fir和end标记数组首尾,核心代码如下
if(value[fir]+value[end]<=W&&(fir!=end)){
tol++;
fir++;
end--;
}else{
tol++;
end--;
}
注意事项:
我在写代码的时候忘了排序这个步骤。。。
理清自己的解题思路,并列下解题步骤,方便调试时更快地找出问题。
参考代码:
#include<bits/stdc++.h> #include<stdio.h> #include<math.h> #include<string.h> #include<algorithm> #include<vector> #include<set using namespace std; typedef long long ll; bool cmp(int a,int b){ return a<b; } int main(){ int W,N; int fir,end; int tol=0; scanf("%d %d",&W,&N); int value[N]; fir=0,end=N-1; for(int i=0;i<N;i++){ scanf("%d",&value[i]); } sort(value,value+N,cmp); while(fir<=end){ if(value[fir]+value[end]<=W&&(fir!=end)){ tol++; fir++; end--; }else{ tol++; end--; } } printf("%d\n",tol); return 0; }
0.0分
3 人评分