递归算法90分,请求大佬支援

P1150 Peter 的烟

FreeDomMan @ 2023-01-28 16:31:08

出错在第三个样例

#include<iostream>
void sum(int n,int k,int &ret);
using namespace std;
int main(){
    int n,k;
    int ret=0;
    cin>>n>>k;
    sum(n,k,ret);
    cout<<ret<<endl;
}
void sum(int n,int k,int &ret){
    ret+=n;
    while(n!=0) {
    return sum(n/k,k,ret);
    }   
}

by Sun_Email @ 2023-01-28 17:15:27

额 之前剩下的烟头算了吗

就例如8根烟,3个烟头换一支烟

然后抽完8支烟之后换两个烟,剩两个烟头

然后再把两支烟抽完,此时剩4个烟头,结果还能在抽一支烟

你的程序输出是10,答案是11

@FreeDomMan


by Sun_Email @ 2023-01-28 17:19:02

#include<iostream>
void sum(int n,int k,int x,int &ret);
using namespace std;
int main(){
    int n,k;
    int ret=0;
    cin>>n>>k;
    sum(n,k,0,ret);
    cout<<ret<<endl;
}
void sum(int n,int k,int x,int &ret){
    ret+=n;
    if(n!=0){
        return sum(n/k+(x+n%k)/k,k,(x+n%k)%k,ret);
    }   
} 

by Sun_Email @ 2023-01-28 17:19:13

这个AC的


by FreeDomMan @ 2023-01-28 22:51:47

哇,谢谢


|