3 条题解

  • 2
    @ 2023-10-4 9:58:53

    算法:先对数组从小到大排序,用 i = 1, j = n 指针指向首尾元素; 如果 a_i+a_j>wa\_i + a\_j > w ,则将 a_ja\_j单独作为一组,指针j-- ;如果a_i+a_jwa\_i + a\_j \leq w, 则将a_ia\_ia_ja\_j分为一组, 指针 i--, j--。 如此重复直到 “取完” 所有元素。

    • 1
      @ 2025-7-2 19:22:47
      #include <bits/stdc++.h>
      using namespace std;
      int x,y,n,a[100005],w,s;
      int main(){
      	cin>>w;
          cin>>n;
          for (int i=1;i<=n;i++){
              cin>>a[i];
          }
        	sort(a+1,a+n+1);
        	for(x=1,y=n;x<=y;){
        		if(a[x]+a[y]<=w){
        			x++;//双指针
      			y--;
      			s++;
        		}
        		else{
        			y--;
        			s++;
        		}
        	}
        	cout<<s;
          return 0;
      }
      
      • 0
        @ 2025-7-4 14:09:29
        #include<bits/stdc++.h>
        using namespace std;
        int w,n;
        int p[30005];
        int ans;
        signed main(){
        	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
        	cin>>w>>n;
        	for(int i=1;i<=n;i++) cin>>p[i];
        	sort(p+1,p+n+1);
        	int l=1,r=n;
        	while(l<=r){//双指针
        		if(p[l]+p[r]>w){//1.
        			r--;//p[r]单独分一组 
        			ans++;
        		}
        		else{//2.
        			l++;r--;
        			ans++;//一起分一组
        		}
        	}
        	cout<<ans;
        	return 0;
        }
        
        • 1

        信息

        ID
        227
        时间
        1000ms
        内存
        256MiB
        难度
        4
        标签
        (无)
        递交数
        249
        已通过
        124
        上传者