CodeForces1343C - Alternating Subsequence - while暴力

题意:一道水题,给出一个序列,要求找出一个子序列,(子序列的要求是:满足正负正负、或者负正负正,以此类推),使得该子序列长度最长和值最大。注意看样例(第一个位置无论正负都得取,因为要保证长度最长)。
PS:但是感觉我这次败给水题了,这题只有800分,我找bug找了2h,加油吧小伙子!

思路:
直接根据正负数所在的区间,找出正数区间最大的数和负数区间最大的数,以此类推,进项相加。
利用两个while进行判断。

注意:
一个就是define和const,另外一个就是while的判断条件应该多加一个i<n,而不是在后面i--,否则会导致死循环。

首先说一下一个很大的问题,就是const和define表示科学计数法的时候,const:可以科学计数法+直接表示数字;define:只能直接写全数字,单独直接科学计数法的话数据会有错,除非加上括号。

#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long ll;

#define inf1 1e9+10
#define inf2 1000000010
const int i1=1e9+10;
const int i2=1000000010;

int main()
{
   cout<<inf1<<endl; // 1e+09
    cout<<inf2<<endl; // 1000000010
   cout<<i1<<endl; // 1000000010
   cout<<i2<<endl; // 1000000010
    return 0;
}

AC代码:

#include <iostream>
#include <string.h>
#include <algorithm>

using namespace std;
typedef long long ll;

const int N=2e5+20;
//#define inf  2147483648
const ll inf=2147483648;
//const ll inf=1e9+10;
ll a[N];

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int n;
        cin>>n;
        int cnt1=0,cnt2=0;
        ll max1=-inf;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            if(a[i]<0)
                cnt1++;
            else
                cnt2++;
            max1=max(max1,a[i]);
        }
        if(cnt1==n||cnt2==n)
        {
            cout<<max1<<endl;
            continue;
        }
        ll sum=0;

//        int x=n-1;
        for(int i=0;i<n;)
        {
//            if(i==x)
//                break;
            bool flag=0;
            max1=-inf;
            while(a[i]>0&&i<n)
                flag=1,max1=max(max1,a[i]),i++;
//            cout<<i<<"  1----"<<max1<<endl;
            if(flag)
                sum+=max1;
            flag=0,max1=-inf;
            while(a[i]<0&&i<n)
                flag=1,max1=max(max1,a[i]),i++;
//            cout<<i<<"  2----"<<max1<<endl;
            if(flag)
                sum+=max1;
        }
        cout<<sum<<endl;
    }
    return 0;
}

//inf 1061109567
//int -2147483648~2147483647 老忘:以后写题注意虽然数int,但是进行运算会出现溢出。

这个是官方题解代码,比我的短,自己代码还需改进,毕竟这是水题。

#include <bits/stdc++.h>

using namespace std;

int main() {
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);
#endif
	
	auto sgn = [&](int x) {
		if (x > 0) return 1;
		else return -1;
	};

	int t;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		vector<int> a(n);
		for (auto &it : a) cin >> it;
		long long sum = 0;
		for (int i = 0; i < n; ++i) {
			int cur = a[i];
			int j = i;
			while (j < n && sgn(a[i]) == sgn(a[j])) {
				cur = max(cur, a[j]);
				++j;
			}
			sum += cur;
			i = j - 1;
		}
		cout << sum << endl;
	}
	return 0;
}
``

猜你喜欢

转载自www.cnblogs.com/OFSHK/p/13196429.html