我有一题有问题,求助大佬!!

B3637 最长上升子序列

Michelle01 @ 2023-07-27 15:05:16

题号:U303676

我的代码

#include <stdio.h>
#include<algorithm>
#include<math.h>
#include<bits/stdc++.h>
using namespace std;

int main(){

    string a[100];
    string b[100];
    int ans = 0;
    int n, k;
    cin >> n >> k;
    bool p = 0;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
    for(int i = 0; i < n; i++){
        if(a[i] != " "){
            ans += a[i].size(); 
        }
        if(ans <= k){
            if(p == 0){
                cout << a[i] << " ";
            }
            if(p == 1){
                cout << endl << a[i] << " ";
            }
            p = 0;
        }
        else{
            cout << endl << a[i] << " ";
            ans = 0;
            p = 1; 
        }

    }
    return 0;
}

我的输出样例不对!!


by xin20110426 @ 2023-07-27 15:21:23

我的代码

#include<bits/stdc++.h>
using namespace std;

int main(){

    string a[100];
    string b[100];
    int now = 0;
    int n, k;
    cin >> n >> k;
    bool p = 0;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
    for(int i = 0; i < n; i++){
        if (now == 0) {
            cout << a[i];
            now = a[i].size();
        } 
        else {
            if (now + a[i].size() <= k) {
                cout << " " << a[i];
                now += a[i].size();
            }
            else {
                cout << endl << a[i];
                now = a[i].size();
            }
        }
    }
    cout << endl;
    return 0;
}

by cq_zry @ 2023-07-27 15:22:32

@Michelle01 USACO的原题


by cq_zry @ 2023-07-27 15:26:26

@Michelle01 这样:

#include<bits/stdc++.h>
using namespace std;
#define int long long 
int n,k;
string s;
signed main(){
    cin>>n>>k;
    int now_where=0;//当前放了多少字符
    while(n--){
        cin>>s;
        if(now_where+s.size()<=k){//放得下
            cout<<s<<" ",now_where+=s.size();
        }
        else{//放不下
            cout<<"\n"<<s<<" ";
            now_where=s.size();
        }
    }
}

by xin20110426 @ 2023-07-27 15:33:22

@cq_zry USACO的哪道题?我也去刷一下


by cq_zry @ 2023-07-27 15:34:36

@xin20110426 不知道,反正就是USACO的,老早以前做的


by Michelle01 @ 2023-07-27 15:43:46

@xin20110426 那请问大佬我的代码哪里有问题


by Michelle01 @ 2023-07-27 15:46:14

@cq_zry 感谢大佬!!,我明白我哪里有问题了!!


by Michelle01 @ 2023-07-27 15:47:26

@xin20110426 我有


by Michelle01 @ 2023-07-27 15:53:25

@cq_zry 大佬,在else判断里那个now_where为什么不能等于0呢?


by cq_zry @ 2023-07-27 15:56:44

@Michelle01 你else是放不下的情况,放不下只能说明now_where+s.size()>k,题目保证了s.size()<=k,那肯定就是now_where>0啊


| 下一页