切水题爆零?
查看原帖
切水题爆零?
1431527
封禁用户楼主2024/11/3 13:38

前言:本体不是题解,是求助!!!

先来看题目,这题目一看就知道:欸,不就是我们亲爱的快慢指针吗,随随便便AC好吧。

我的思路是这么想的:由于这个题目给的范围太大,开这么大数组100%RE,然后就用 vector nums[n],输入完了再定义一个left和fast指针对吧,让然后就循环再定义两个函数用max比较对吧,最后输出。

这边就是第一次爆零的CODE:

#include <iostream>
#include <vector>
using namespace std;

int main(){
    int n;
    cin >> n;
    vector<int> nums(n);
    for(int i = 0 ; i < n ; i ++){
        cin >> nums[i];
    }
    
    int slow = 0, fast = 1;
    int ans = 0, cnt = 0;
    
    while(fast < n){
        if(nums[fast] - nums[fast - 1] == 1){
            cnt++;
            fast++;
        }
        else{
            ans = max(ans, cnt); 
            cnt = 0;
            slow = fast;
            fast++;
        }
    }
    
    ans = max(ans, cnt);
    cout << ans << endl;
    
    return 0;
}

看来看去没看出来啥大毛病,放到编译器上一运行,欸?

5
1 2 3 4 5
4

--------------------------------
Process exited after 3.579 seconds with return value 0 (15.62 ms cpu time, 604 KB mem used).

Press ANY key to exit...

怎么是4,于是想到一个投机取巧的办法:

#include <iostream>
#include <vector>
using namespace std;

int main(){
	int n;
	cin >> n;
	vector <int> nums(n);
	for(int i = 0 ; i < n ; i ++){
		cin >> nums[i];
	}
	
	int slow = 0, fast = 1;
	int ans = 0, cnt = 0;
	while(fast < n){
		if(nums[fast] - nums[fast - 1] == 1){
			cnt ++;
			fast ++;
		}
		else{
			ans = max(ans, cnt);
			slow = fast;
			fast ++;
		}
		ans = max(ans, cnt);
	}
	
	ans = max(ans, cnt);
	cout << ans + 1 << endl;   //这边加1输出
	
	return 0;
}

不错,拿到一个点,20分。但是还是没A。。。

求解必关!!!!!!!!!!!!!

2024/11/3 13:38
加载中...