ACM做题笔记

QiuNanRima 发布于 2026-10-13 255 次阅读 6914 字 最后更新于 2026-10-26 预计阅读时间: 31 分钟


本人刚刚开始接触ACM以及相关方面的事物,故想写笔记记录下易错点来防止再犯

持续更新中.....

Longest Ordered Subsequence(10001)

hnu acm练习的需要思考的第一个题目(((

我的代码:

#include<iostream>
#include<vector>

using namespace std;

int main(){
    int n;
    cin >> n;
    vector<int> seqs;
    seqs.resize(n);
    for(int i=0;i<n;i++){
        cin>>seqs[i];
    }
    
    vector<int> num(n,1);
    for(int i=0;i<n;i++){
        if(i==0){
            num[i] = 1;
            continue;
        }
        for(int n1=0;n1<i;n1++){
            if(seqs[n1]<seqs[i]&&num[i]<=num[n1]){
                num[i]= num[n1] + 1;
            }
        }
    }
    int max=0;
    for(int i=0;i<n;i++){
        if(num[i]>max){
            max = num[i];
        }
    }
    cout<<max;


}

效率不是很高(力大砖飞),但确实AC了,也就没管了

思路:利用递推的思路一个个算出来

Dissatisfying Lift(10003)

(为什么没有10002?因为我还不会写)

我的第一版代码

#include<iostream>
#include<vector>

using namespace std;

int main(){
    int times;
    cin>>times;
    for(int i=0;i<times;i++){
        
        int M,a,b;
        cin>>M>>a>>b;
        vector<int> K(M);
        for(int i=0;i<M;i++){
            cin>>K[i];
        }
        
        //Every tenant went up N floors would make the dissatisfied degree rise 
        //N * a + 0.5 * N * (N - 1) degrees, 
        //and every tenant went down N floors would make the dissatisfied degree rise 
        //N * b + 0.5 * N * (N - 1) degrees.
        vector<double> disat(M,0);
        for(int i=0;i<M;i++){
            for(int i1=0;i1<M;i1++){
                if(i1<i){
                    int N = i -i1;
                    disat[i] += K[i1]*(N * b + 0.5 * N * (N - 1)); 
                }else{
                    int N = i1 -i;
                    disat[i] += K[i1]*(N * a + 0.5 * N * (N - 1)); 
                }
            }
        }
        
        double ans[2];
        
        for(int i=0;i<M;i++){
            if(i==0||ans[0]>disat[i]){
                ans[1] = i + 1;
                ans[0] = disat[i];
            }
        }
        
        cout<<ans[1]<<endl;
    }
}

思路也是非常简洁易懂,但是复杂度太大了,直接TLE

修改后版

#include<iostream>
#include<vector>

using namespace std;

int main(){
    int times;
    cin>>times;
    for(int i=0;i<times;i++){
        
        int M,a,b;
        cin>>M>>a>>b;
        vector<int> K(M);
        for(int i=0;i<M;i++){
            cin>>K[i];
        }
        
        //Every tenant went up N floors would make the dissatisfied degree rise 
        //N * a + 0.5 * N * (N - 1) degrees, 
        //and every tenant went down N floors would make the dissatisfied degree rise 
        //N * b + 0.5 * N * (N - 1) degrees.
        vector<double> disat(M,0);
        long long PD=0,PU=0,DD=0,DU=0;
        for(int i=1;i<M;i++){
            int N = i;
            disat[0] = K[i] * (N * a + 0.5 * N * (N - 1));
            /*for(int i1=0;i1<M;i1++){
                if(i1<i){
                    int N = i -i1;
                    disat[i] += K[i1]*(N * b + 0.5 * N * (N - 1)); 
                }else{
                    int N = i1 -i;
                    disat[i] += K[i1]*(N * a + 0.5 * N * (N - 1)); 
                }
            }*/
            
        }
        PD += K[0];
        //DD += K[0]*0;
        for(int i=1;i<M;i++){
            PU += K[i];
            DU += K[i]*i;
        }
        /*化简后有
        sum (b + x) = sum b + sum x = b (text{下方总人数}) + (text{下方住户原本的总距离})
        sum (1 - a - y) = (1 - a) (text{上方总人数}) - (text{上方住户原本的总距离})
        
        ​由上述数学推导可知,为了在 O(1) 时间内算出下一层的总代价,我们在遍历到第 i 层时,
        手里必须握着四个关键变量:
        ​P_{down}:第 1 到 i 层的总人数。
        ​D_{down}:第 1 到 i 层的住户,到达第 i 层的距离总和。
        ​P_{up}:第 i+1 到 M 层的总人数。
        ​D_{up}:第 i+1 到 M 层的住户,到达第 i 层的距离总和。
        ​只要有这四个变量,电梯移到第 i+1 层时的总代价就是
        Cost(i+1) = Cost(i) + b P_{down} + D_{down} + (1-a)  P_{up} - D_{up}
        
        最巧妙的一步来了:计算完 Cost(i+1) 后,如何更新这四个变量,让它们变成相对于第 i+1 层的状态?
        ​对于下方的住户( P_{down} 和 D_{down} ):
        ​因为电梯上移了一层,原本在下方的人,每人都要多走一层。
        所以原有的总距离增加了 P_{down}:D_down = D_down + P_down。
        ​第 i+1 层的住户,原本属于“上方”,现在电梯停在他们这一层了,接下来如果电梯再去 i+2 层,他们就会变成“下方”的人。所以下方人数增加了:P_down = P_down + K[i+1]。
        ​对于上方的住户( P_{up} 和 D_{up} ):
        ​因为电梯上移了一层,原本在上方的人,每人都可以少走一层。
        所以原有的总距离减少了 P_{up}:D_up = D_up - P_up。
        ​第 i+1 层的住户已经被划归到下方了,所以上方人数减少了:P_up = P_up - K[i+1]。
        */
        
        for(int i=1;i<M;i++){
            disat[i] = disat[i-1]+ b*PD +DD +(1-a)*PU -DU;
            DD = DD +PD;
            PD += K[i];
            DU = DU -PU;
            PU -= K[i];
        }
        
        double ans[2];
        
        for(int i=0;i<M;i++){
            if(i==0||ans[0]>disat[i]){
                ans[1] = i + 1;
                ans[0] = disat[i];
            }
        }
        
        cout<<ans[1]<<endl;
    }
}

根据计算式化简后可以得到更简单的不满意度和住户的关系,计算量大大减少(感谢gemini大人,我个猪头根本想不到化简的路子)

Prime Test(10007)

最无力的一集

第一版直接暴力求解

也是直接TLE(5015ms)

最终版(砍了一般的计算量,但还是不够)

#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main(){
    int n;
    cin >> n;
    vector<long long> nums(n);
    for(int i=0;i<n;i++){
        cin >> nums[i];
    }
    
    for(int i = 0; i < n; i++){
        long long num = nums[i];
        
        // 单独处理 2
        if (num % 2 == 0) {
            cout << 2 << endl;
            continue;
        }
        
        // 从 3 开始,每次加 2(只检查奇数)
        bool is_prime = true;
        long long min_factor = 0;
        for(long long d = 3; d <= ceil(sqrt(num)); d += 2){
            if(num % d == 0){
                min_factor = d;
                is_prime = false;
                break;
            }
        }
        
        if(is_prime){
            cout << "Prime" << endl;
        } else {
            cout << min_factor << endl;
        }
    }
    return 0;
}

依旧TLE

这个题要用到费马小定理啥的去解,但是目前我还没有学到那里,所以等我学完知识再回来弄这个题

Game of Connections(10009)

思路:使用递归的想法

当2n的圆环被分割开后,余下的可以再次组成两个圆环。依次继续递归计算直到n=1;

#include<iostream>
#include<vector>

using namespace std;

inline int calc(int);

int main(){
    vector<int> ans(0,0);
    for(;true;){
        int input;
        cin>> input;
        if(input==-1){
            break;
        }
        ans.push_back(calc(input));
    }
    for(int i=0;i<ans.size();i++){
        cout<<ans[i]<<endl;
    }
}

inline int calc(int num){
    if(num==0){
        return 1;
    }
    if(num==1){
        return 1;
    }
    if(num==2){
        return 2;
    }
    int ans =0;
    for(int i=0;i<num;i++){
        ans+=calc(i)*calc(num-1-i);
    }
    return ans;
}

也是直接TLE,但抛开时间限制不谈,这个代码也是错误的

实际上这是一个卡特兰数的计算,当n=100时,最终的值也远远大于long long int所能储存的范围,甚至__int128都不行(其实__int128装的下也要手写大数运算,hnu的oj太老了,比我都大,根本不支持这些特性)

#include<vector>
#include<iostream>

using namespace std;

typedef vector<int> BigInt;
inline BigInt add(BigInt,BigInt);
inline BigInt mul(BigInt,BigInt);
inline BigInt mul(BigInt,int);
inline void printbi(BigInt);
inline BigInt calc(int,vector<BigInt>&);

int main(){
    vector<BigInt> ans(0,BigInt(1,0));
    vector<BigInt> cache(101,BigInt(1,0));
    
    for(;true;){
        int input;
        cin>> input;
        if(input==-1){
            break;
        }
        ans.push_back(calc(input,cache));
    }
    for(int i=0;i<ans.size();i++){
        printbi(ans[i]);
    }
}

inline BigInt calc(int num,vector<BigInt>& cache){
    if(num==0){
        return BigInt(1,1);
    }
    if(num==1){
        return BigInt(1,1);
    }
    if(num==2){
        return BigInt(1,2);
    }
    if(cache[num]!=BigInt(1,0)){
        return cache[num];
    }
    BigInt ans(1,0);
    for(int i=0;i<num;i++){
        ans = add(ans,mul(calc(i,cache),calc(num-1-i,cache)));
    }
    cache[num]=ans;
    
    return ans;
    
    
}

inline BigInt add(BigInt a,BigInt b){
    int length = max(a.size(),b.size());
    a.resize(length,0);
    b.resize(length,0);
    BigInt res;
    int sum = 0;
    for(int i=0;i<length;i++){
        sum += a[i] +b[i];
        res.push_back(sum%10);
        sum/=10;
        if(i==length-1&&sum>0){
            res.push_back(sum);
        }
    }
    return res;
    
}

inline BigInt mul(BigInt a,int b){
    //要求:b是一个个位数
    BigInt res(a.size()+1,0);
    for(int i=0;i<a.size();i++){
        int tmp = b*a[i]+res[i];
        res[i] = tmp%10;
        if(tmp/10!=0){
            res[i+1]=(tmp/10);
        }
    }
    for(int i=a.size();i>0;i--){
        if(res[i]==0){
            res.pop_back();
        }else{
            break;
        }
    }
    return res;
}

inline BigInt mul(BigInt a,BigInt b){
    int length = a.size()+b.size();
    BigInt res(length,0);
    for(int i=0;i<b.size();i++){
        BigInt tmp = mul(a,b[i]);
        tmp.insert(tmp.begin(),i,0);
        res = add(res,tmp);
    }
    while(res.size()>1&&res.back()==0){
        res.pop_back();
    }
    return res;
}

inline void printbi(BigInt a){
    for(int i=a.size()-1;i>=0;i--){
        cout<<a[i];
    }
    cout<<endl;
}

这是最终版,包含了简易的大数模拟以及运算,同时实现了卡特兰数的缓存机制

先讲讲缓存:由于每次计算递归都会到重复的部分,如果将这些重复的部分放入缓存中,可以大大减少重复的计算量

再讲讲大数模拟,我使用vector数组进行的模拟,对于其存储的某个数,以低位在前,高位在后的方式储存。例如:对于数字1234,在数组中num[0]=4,num[1]=3,num[2]=2,num[3]=1的顺序存储

为什么要这么做呢?这样的话对于每个数,它们的个位都是对齐的,不会乱飘。

存储解决了,接下来就是解决运算了

加法

inline BigInt add(BigInt a,BigInt b){
    int length = max(a.size(),b.size());
    a.resize(length,0);
    b.resize(length,0);
    BigInt res;
    int sum = 0;
    for(int i=0;i<length;i++){
        sum += a[i] +b[i];
        res.push_back(sum%10);
        sum/=10;
        if(i==length-1&&sum>0){
            res.push_back(sum);
        }
    }
    return res;
    
}

首先我将答案数组长度设为a,b两个数组的最大长度,然后将两个数组均调整为最大值,为什么呢?对于两个数相加,答案的位数最多比较大数多一;而且统一为最长的位数后,相加时不会out of index。

然后对于每一位,我们进行先取答案数组的相应位与a,b数组的相应位相加,然后进位,将进的位放入答案的下一位中

然后当运算到最后一位时,判断是否要进位。

乘法

乘法我写了两个部分(感觉ai给的解决方案有点复杂,于是自己想了个容易理解的),第一个是模拟大数与个位整数的运算

inline BigInt mul(BigInt a,int b){
    //要求:b是一个个位数
    BigInt res(a.size()+1,0);
    for(int i=0;i<a.size();i++){
        int tmp = b*a[i]+res[i];
        res[i] = tmp%10;
        if(tmp/10!=0){
            res[i+1]=(tmp/10);
        }
    }
    for(int i=a.size();i>0;i--){
        if(res[i]==0){
            res.pop_back();
        }else{
            break;
        }
    }
    return res;
}

第二个个是大数与大数的乘法运算

inline BigInt mul(BigInt a,BigInt b){
    int length = a.size()+b.size();
    BigInt res(length,0);
    for(int i=0;i<b.size();i++){
        BigInt tmp = mul(a,b[i]);
        tmp.insert(tmp.begin(),i,0);
        res = add(res,tmp);
    }
    while(res.size()>1&&res.back()==0){
        res.pop_back();
    }
    return res;
}

对于第一个函数,我们可以看到其实就是简单的各个位与整数相乘然后再判断进位的思路。(其实也可以用模拟大数的加法来处理)

第二个函数,就是将第二个大数的每一位拆开来分别相乘,这也是为什么我写第一个工具函数的原因,例如:1234*567=1234*500+1234*60+1234*7=1234*5*100+1234*6*10+1234*7

也就是说,每个乘法都可以拆成一个数和个位数的乘法。

对于×10^i,直接在数组的0位前插入i个0即可

打印

inline void printbi(BigInt a){
    for(int i=a.size()-1;i>=0;i--){
        cout<<a[i];
    }
    cout<<endl;
}

没说的,直接上代码即可

Recaman's Sequence(10010)

看着很像Game of Connections(10009)吧?

但是这个题如果用那个递归函数的方法做会直接爆栈

为什么呢?

Gemini的解释:

​如果第一个输入的数字就是 500000,此时缓存是全空的:

​calc(500000) 查表:未计算 -> 挂起当前函数,调用 calc(499999)

​calc(499999) 查表:未计算 ->挂起当前函数,调用 calc(499998)

​……

​一路调用到 calc(0)

​在 calc(0) 算完并开始逐层返回、填入 cache 之前,这 50 万个函数必须同时保存在系统的调用栈(Call Stack)中。

​每个函数调用在栈中都有一个栈帧(保存参数、局部变量、返回地址等),大约占用 32 ~ 64 字节。

​500000 × 48Bytes ≈24MB

​OJ 评测机和操作系统的默认栈空间通常只有 8 MB(Windows 本地甚至只有 1 MB)。在代码拿到第一个返回值、往缓存写下第一个数字之前,调用栈就已被彻底撑爆,直接触发段错误(RE)。

简单来说就是雪球越滚越大,把上限挤爆了

那这个地方就要用递推了,函数用完一次立即释放,不会存在爆栈的风险

#include<iostream>
#include<vector>

using namespace std;

inline void pre(vector<long long>&,vector<bool>& );

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    vector<long long> cache(500001,0);
    vector<long long> ans;
    vector<bool> vis(100000000,false);
    vis[0]=true;
    pre(cache,vis);
    for(;true;){
        int input;
        cin>> input;
        if(input==-1){
            break;
        }
        ans.push_back(cache[input]);
    }
    for(int i=0;i<ans.size();i++){
        cout<<ans[i]<<'\n';
    }
    
}

inline void pre(vector<long long>& cache,vector<bool>& vis){
    for(int m=0;m<500001;m++){
        if(m==0){
            cache[m] = 0;
            continue;
        }
        long long tmp = cache[m-1] - m;
        if(tmp<=0||vis[tmp]){
            tmp+=2*m;
        }
        cache[m]=tmp;
        vis[tmp]=true;
    }
}

在开始的时候就把所有结果算完,然后再按需调用

再讲讲要注意的点几个点:

  • hnu的测评机有点太老了,练nullptr都没有,需要注意
  • 对于某个数是否出现过可以用布尔标记数组

再补一个递推和递归的区别:

递推(Bottom-up)与递归(Top-down)的核心区别在于计算方向与系统底层的执行机制。

维度 递推(Iterative) 递归(Recursive)
计算方向 自底向上:从已知的初始状态出发,逐步向前计算出目标值。 自顶向下:从最终问题出发,逐层分解为子问题,触底后再逐层回溯返回。
实现机制 循环语句(for / while)驱动。 函数自身调用自身。
调用栈占用 O(1)。只处于当前函数帧,不消耗额外栈空间。 O(深度)。每调用一层都需要在系统调用栈中压入一个栈帧。
爆栈风险 零风险。数据主要存储在堆或全局区,受限于机器总内存。 高风险。递归深度超过数万至数十万时必定触发栈溢出(Stack Overflow / RE)。
执行开销 极小。纯算术运算与内存寻址,对 CPU 缓存和指令预测非常友好。 偏大。每次调用都有保护现场、压栈、参数传递、跳转及弹栈的系统开销。

以斐波那契数列为例

递推实现(自底向上)
从 f(0), f(1) 开始,一步步往后累加:

int f[N];
f[0] = 0; f[1] = 1;
for (int i = 2; i <= n; ++i) {
    f[i] = f[i - 1] + f[i - 2]; // 状态依赖明确,直接循环求解
}

递归实现(自顶向下)
从 f(n) 开始,不断向子状态询问:

int f(int n) {
    if (n <= 1) return n;
    return f(n - 1) + f(n - 2); // 拆解问题,深入调用直到触发基准条件
}

选型原则

  • 必须/优先使用递推的场景
    • 状态转移链条长且线性(如序列生成、前缀和、单序列 DP)。
    • 规模 N ≥ 105 的数值计算问题,规避系统调用栈深度上限。
    • 追求极致常数优化、避免函数调用开销的性能敏感路径。
  • 优先使用递归的场景
    • 数据结构本身具有递归嵌套性质(如树的遍历、二叉搜索树、表达式解析)。
    • 搜索与回溯算法(如 DFS、全排列、八皇后、图的连通块遍历)。
    • 分治算法(如归并排序、快速排序、大整数乘法),自顶向下切分问题更贴近数学抽象。

Calendar(10013)

初版(WA)

//Given the number of days that have elapsed since January 1, 2000 A.D,
//your mission is to find the date and the day of the week.

#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main(){
	vector<string> ans;
	while(true){
		int input;
		cin>>input;
		if(input == -1){
			break;
		}
		//base January 1, 2000
		int years=0,months=0,weeks=0,days = input;
		
		while(true){
			if(!(days>=366)){
				break;
			}
			if((years+1)%4==0){
				days-=366;
				years++;
				break;
			}
			days -= 365;
			years++;
			
		}
		
		for(int i=1;true;i++){
			if(!(days>=31)){
				break;
			}
			//1,3,5,7,8,10,12 -- 31
			//2 -- if leap?
			
			switch (i) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				days -= 31;
				months++;
				break;
			case 2:
				if(years%4==0){
					days -= 29;
				}else{
					days -= 28;
				}
				months++;
				break;
			default:
				days -= 30;
				months++;
				break;
			}
			
		}
		years += 2000;
		months += 1;
		days += 1;
		string a="";
		a += to_string(years) + "-";
		if(months<10){
			a += "0"+to_string(months) + "-";
		}else{
			a += to_string(months) + "-";
		}
		if(days<10){
			a += "0" + to_string(days);
		}else{
			a += to_string(days);
		}
		
		weeks = input % 7;
		switch (weeks) {
		case 1:
			a += " Tuesday";
			break;
		case 2:
			a += " Wednesday";
			break;
		case 3:
			a += " Thursday";
			break;
		case 4:
			a += " Friday";
			break;
		case 5:
			a += " Saturday";
			break;
		case 6:
			a += " Sunday";
			break;
		case 0:
			a += " Monday";
			break;
		default:
			//TODO
			break;
		}
		ans.push_back(a);
	}
	for(int i=0;i<ans.size();i++){
		cout<<ans[i]<<endl;
	}
}

WA原因:

  • 2001.1.1日不是周一(孩子们细节决定成败)
  • 多余了 break,导致跨多个闰年的输入(比如 input = 1730)会算错;
  • %4==0 没排除整百年(2100 不是闰年),虽然 2000–2099 区间内没问题,但严格起来要 %400==0 || (%4==0 && %100!=0);
  • 月份循环用 days >= 31 作为判断也不对(2 月、4 月、6 月、9 月、11 月都少于 31 天),应该按当月的实际天数判断,否则 days = 30 时进入 2 月会减成负数

final:

//Given the number of days that have elapsed since January 1, 2000 A.D,
//your mission is to find the date and the day of the week.

#include<iostream>
#include<vector>
#include<string>
#include<sstream>

using namespace std;

string to_string(int v){
    std::ostringstream oss;
    oss << v;
    return oss.str();
}

// 判断闰年
bool isLeap(int y){
    return (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
}

// 某年某月的天数,m 取 1..12
int daysInMonth(int y, int m){
    static const int d[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    if(m == 2 && isLeap(y)) return 29;
    return d[m];
}

int main(){
    vector<string> ans;

    // 2000-01-01 是 Saturday,input % 7 == 0 即 Saturday
    static const char* week[] = {
        "Saturday","Sunday","Monday","Tuesday",
        "Wednesday","Thursday","Friday"
    };

    while(true){
        int input;
        cin >> input;
        if(input == -1) break;

        int days  = input;
        int years = 0;    // 相对 2000 的偏移

        // 减整年:按当前年(2000+years)的实际天数判断
        while(true){
            int y  = 2000 + years;
            int yd = isLeap(y) ? 366 : 365;
            if(days < yd) break;
            days -= yd;
            years++;
        }

        int months = 0;   // 相对 1 月的偏移
        // 减整月:按当月的实际天数判断
        while(true){
            int y  = 2000 + years;
            int m  = months + 1;          // 1..12
            int md = daysInMonth(y, m);
            if(days < md) break;
            days -= md;
            months++;
        }

        int year  = 2000 + years;
        int month = months + 1;
        int day   = days + 1;

        // 拼 "YYYY-MM-DD"
        string a = "";
        a += to_string(year) + "-";
        if(month < 10) a += "0" + to_string(month) + "-";
        else           a += to_string(month) + "-";
        if(day < 10)   a += "0" + to_string(day);
        else           a += to_string(day);

        // 星期
        a += " ";
        a += week[input % 7];

        ans.push_back(a);
    }

    for(size_t i = 0; i < ans.size(); i++){
        cout << ans[i] << endl;
    }

    return 0;
}

(手动实现to_string的原因:hnu的oj只支持到cpp98)

The Triangle(10014)

动态规划(有点高中数组递推题目的感觉)

初版

/*Your program is to read from standard input. 
The first line contains one integer T, 
the number of test cases,
for each test case: 
the first line contain a integer N: 
the number of rows in the triangle. 
The following N lines describe the data of the triangle. T
he number of rows in the triangle is > 1 but <= 100.
The numbers in the triangle, all integers, are between 0 and 99.*/

#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>

using namespace std;

int main(){
    int times;
    cin>>times;
    for(int i=0;i<times;i++){
        vector<vector<int>> tri;
        int times;
        cin>>times;
        for(int i=1;i<=times;i++){
            //scan 1 nums
            vector<int> tmp;
            for(int i1=1;i1<=i;i1++){
                int input;
                cin>>input;
                tmp.push_back(input);
            }
            tri.push_back(tmp);
        }
        //analyse: letter->lines, nums->rows   
        //a1->b1/b2
        //b1->c1/c2  b2->c2/c3
        //c1->d1/d2  c2->d2/d3  c3->d3/d4
        vector<vector<int>> maxs = tri;
        for(int i=0;i<times-1;i++){
            
            //{S x n}max = max({S x-1 n}max ,{S x-1 n-1}max) + Xn
            //maxs[0][0]就是tri[0][0]
            //从maxs[1][0]开始算
            
            /*
        cast 1L -> 0(i)
             2L -> 1
             ...
             
             1R -> 0(i1)
             2R -> 1
             ...
            */
            for(int i1=0;i1<i;i1++){
                //0,1,2,3
                if(i1==0){
                    maxs[i+1][0] = tri[i+1][0]+ maxs[i][0];
                }else if(i1==i-1){
                    maxs[i+1][i1] = tri[i+1][i1]+ maxs[i][i1 - 1];
                }else{
                    maxs[i+1][i1] = tri[i+1][i1] + max(maxs[i][i1],maxs[i][i1-1]);
                }
            }
            
        }
        sort(maxs[i-1].begin(),maxs[i-1].end());
        cout<<maxs[i-1][0];
    }
}

问题:

  • 变量遮蔽(内外变量名相同导致混乱(混乱的是我))
  • sort后[0]是min值,要用.back()
  • 循环上限问题
    为什么这里不对?
    你在循环体内更新的是 maxs[i+1][i1],也就是第 i+1 行的数据。
    当 i = 0 时,你在算下标为 1 的那一行(即第 2 行,有 2 个元素,下标是 0 和 1)。但因为你写了 i1 < i(即 i1 < 0),这个循环一次都不会执行!
    对于下标为 i+1 的这一行,它的元素下标是从 0 一直到 i+1 的。

修正后:

/*Your program is to read from standard input. 
The first line contains one integer T, 
the number of test cases,
for each test case: 
the first line contain a integer N: 
the number of rows in the triangle. 
The following N lines describe the data of the triangle. T
he number of rows in the triangle is > 1 but <= 100.
The numbers in the triangle, all integers, are between 0 and 99.*/

#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>

using namespace std;

int main(){
    int times;
    cin>>times;
    for(int n=0;n<times;n++){
        vector<vector<int> > tri;
        int times0;
        cin>>times0;
        for(int i=1;i<=times0;i++){
            //scan 1 nums
            vector<int> tmp;
            for(int i1=1;i1<=i;i1++){
                int input;
                cin>>input;
                tmp.push_back(input);
            }
            tri.push_back(tmp);
        }
        //analyse: letter->lines, nums->rows   
        //a1->b1/b2
        //b1->c1/c2  b2->c2/c3
        //c1->d1/d2  c2->d2/d3  c3->d3/d4
        vector<vector<int> > maxs = tri;
        for(int i=0;i<times0-1;i++){
            
            //{S x n}max = max({S x-1 n}max ,{S x-1 n-1}max) + Xn
            //maxs[0][0]就是tri[0][0]
            //从maxs[1][0]开始算
            
            /*
        cast 1L -> 0(i)
             2L -> 1
             ...
             
             1R -> 0(i1)
             2R -> 1
             ...
            */
            for(int i1=0;i1<=i+1;i1++){
                //0,1,2,3
                if(i1==0){
                    maxs[i+1][0] = tri[i+1][0]+ maxs[i][0];
                }else if(i1==i+1){
                    maxs[i+1][i1] = tri[i+1][i1]+ maxs[i][i1 - 1];
                }else{
                    maxs[i+1][i1] = tri[i+1][i1] + max(maxs[i][i1],maxs[i][i1-1]);
                }
            }
            
        }
        sort(maxs[times0-1].begin(),maxs[times0-1].end());
        cout<<maxs[times0-1].back()<<"\n";
    }
}

ps: cpp98里面记得把两个连着的‘>’分开,不然会认为是操作符

Self Numbers(10015)

初版:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
/*For any positive integer n,
define d(n) to be n plus the sum of the digits of n.
(The d stands for digitadition, a term coined by Kaprekar.) 
For example, d(75) = 75 + 7 + 5 = 87.*/
typedef vector<int> splits;
inline splits split(int);
inline int clac_d(int);

int main(){
    vector<bool> hashmap(10001,true);
    for(int i=0;true;i++){
        int tmp = clac_d(i);
        if(tmp<=10000){
            hashmap[tmp] = false;
        }else{
            break;
        }
    }
    for(int i=1;i<=10000;i++){
        if(hashmap[i]){
            cout<<i<<"\n";
        }
    }
}

splits split (int input){
    // for only positive numbers
    splits ans;
    while(true){
        ans.push_back(input%10);
        input /= 10;
        if(input == 0)
            break;
    }
    return ans;
}

int clac_d(int input){
    splits tmp = split(input);
    int ans = input;
    for(int i=0;i<tmp.size();i++){
        ans += tmp[i];
    }
    return ans;
}

问题:我假设了 calc_d(i) 是随着 i 的增加而单调递增的,当 tmp > 10000 就终止循环。但实际上 calc_d(n) 并不是单调递增的。
BUT!!!实际上由于进位的存在,一个数加上它的各位数字之和可能会突然变小。(e.g. 9999和10000)

最终版

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
/*For any positive integer n,
define d(n) to be n plus the sum of the digits of n.
(The d stands for digitadition, a term coined by Kaprekar.) 
For example, d(75) = 75 + 7 + 5 = 87.*/
typedef vector<int> splits;
inline splits split(int);
inline int clac_d(int);

int main(){
    vector<bool> hashmap(10001,true);
    for(int i=0;i<10000;i++){
        int tmp = clac_d(i);
        if(tmp>10000){
            continue;
        }
        hashmap[tmp] = false;
    }
    for(int i=1;i<10000;i++){
        if(hashmap[i]){
            cout<<i<<"\n";
        }
    }
}

splits split (int input){
    // for only positive numbers
    splits ans;
    while(true){
        ans.push_back(input%10);
        input /= 10;
        if(input == 0)
            break;
    }
    return ans;
}

int clac_d(int input){
    splits tmp = split(input);
    int ans = input;
    for(int i=0;i<tmp.size();i++){
        ans += tmp[i];
    }
    return ans;
}

Polar Explorer(10016)

什么叫做有侵略性的体味啊(((

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

/*struct pst{
    public:
        int radius=0,gallons=0,angle=0;
        bool end_=false;
};*/

struct pst{
    int radius;
    int gallons;
    int angle;
    bool end_;
    pst() : radius(0), gallons(0), angle(0), end_(false) {}
};

inline pst handle_input();
inline double getlength(pst);
const double pi = 3.14159;
int main(){
    while(1){
        pst input = handle_input();
        if(input.end_)
            break;
        double length = getlength(input);
        if(length*5*2>input.gallons){
            cout<<"YES "<<static_cast<int>(input.gallons-length*5);
        }else{
            cout<<"NO "<<static_cast<int>(input.gallons/5.00);
        }
    }
    return 0;
}

/*Input to this problem will consist of a (non-empty) series of up to 100 data sets. 
Each data set will be formatted according to the following description, 
and there will be no blank lines separating data sets.
A single data set has 3 components:
Start line - A single line, "START".
Input line - A single line, "X Y Z", where:
X : (1 <= X <= 100) is the radius of your planet in integer miles
Y : (0 <= Y <= 100) is the amount of gasoline in your planet-rover in integer gallons
Z : (0 <= Z <= 360) is an angle separating you from the crash site in integer degrees

End line - A single line, "END".
Following the final data set will be a single line, "ENDOFINPUT".
Take note of the following:
The circumference of a circle in terms of its radius, r, is known to be 2πr
Assume that π = 3.14159*/
pst handle_input(){
    pst ans;
    string ss;
    cin>>ss;
    if(ss=="ENDOFINPUT"){
        ans.end_ = true;
        return ans;
    }
    if(ss=="START"){
        cin>>ans.radius>>ans.gallons>>ans.angle;
    }
    cin>>ss;
    return ans;
}

double getlength(pst input){
    double primeter = input.radius * 2 * pi;
    if(input.angle>180){
        input.angle -= 180;
    }
    return (primeter*input.angle)/360;
}

直接给修改版吧,哪里错了我都打在注释里了

#include<iostream>
#include<vector>
#include<algorithm>
#include<sstream>

using namespace std;

/*
cpp 98 又发力了,这谁能绷住
struct pst{
	public:
		int radius=0,gallons=0,angle=0;
		bool end_=false;
};*/

struct pst{
	int radius;
	int gallons;
	int angle;
	bool end_;
	pst() : radius(0), gallons(0), angle(0), end_(false) {}
};

inline pst handle_input();
inline double getlength(pst&);
inline string to_str(int);
const double pi = 3.14159;
vector<string> ans;
int main(){
	while(1){
		pst input = handle_input();
		if(input.end_)
			break;
		double length = getlength(input);
		//是1加仑5英里,不是1英里5加仑
		if((length*2)/5<=input.gallons){
			ans.push_back("YES "+to_str(static_cast<int>(input.gallons-length*2/5)));
		}else{
			ans.push_back("NO "+to_str(input.gallons*5));
		}
	}
	for(int i=0;i<ans.size();i++){
		cout<<ans[i]<<"\n";
	}
	return 0;
}

/*Input to this problem will consist of a (non-empty) series of up to 100 data sets. 
Each data set will be formatted according to the following description, 
and there will be no blank lines separating data sets.
A single data set has 3 components:
Start line - A single line, "START".
Input line - A single line, "X Y Z", where:
X : (1 <= X <= 100) is the radius of your planet in integer miles
Y : (0 <= Y <= 100) is the amount of gasoline in your planet-rover in integer gallons
Z : (0 <= Z <= 360) is an angle separating you from the crash site in integer degrees

End line - A single line, "END".
Following the final data set will be a single line, "ENDOFINPUT".
Take note of the following:
The circumference of a circle in terms of its radius, r, is known to be 2πr
Assume that π = 3.14159*/
pst handle_input(){
	pst ans;
	string ss;
	cin>>ss;
	if(ss=="ENDOFINPUT"){
		ans.end_ = true;
		return ans;
	}
	if(ss=="START"){
		cin>>ans.radius>>ans.gallons>>ans.angle;
	}
	cin>>ss;
	return ans;
}

double getlength(pst& input){
	double primeter = input.radius * 2 * pi;
	if(input.angle>180){
		//input.angle -= 180;错误,要用360度来减
		input.angle = 360 - input.angle;
	}
	return (primeter*input.angle)/360;
}

string to_str(int v){
	std::ostringstream oss;
	oss << v;
	return oss.str();
}
此作者没有提供个人介绍。
最后更新于 2026-10-26