想问问这个代码为什么会超时
查看原帖
想问问这个代码为什么会超时
1048629
Missnovdoes楼主2024/4/10 23:09
#include <bits/stdc++.h>
using namespace std;
#define quc ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
 
int main()
{
    quc;
    int t;
    cin >> t;
    while (t--)
    {
        long long n, k;
        cin >> n >> k;
        deque<int> a(n);
        for (int i = 0; i < n; i++) 
        {
            cin >> a[i];
        }
        long long sunk = 0;
        long long i = 0;
        while (!a.empty() && k > 0) 
        {      
            if (a.size() == 1)
            {
                if (k >= a.front())
                {
                    sunk++;
                    break;
                }
            }
            else if (a.front() <= a.back()) 
            {
                k -= a.front() * 2;
                int ac = a.front();
                a.pop_front();
                if (i % 2 == 0)
                {
                    k++;
                    if (a.size() == 0 || k < 0)
                    {
                        break;
                    }
                    a.back()++;
                    i += ac;
                }
                if (k < 0)
                {
                    break;
                }
                sunk++;
                if (a.size() == 0 || k <= 0)
                {
                    break;
                }
                a.back() -= ac;
            } 
            else
            {
                k -= a.back() * 2;
                int ac = a.back();
                a.pop_back();
                if (i % 2 != 0)
                {
                    k++;
                    if (a.size() == 0 || k < 0)
                    {
                        break;
                    }
                    a.front()++;
                    i += ac;
                }
                if (k < 0)
                {
                    break;
                }
                sunk++;
                if (a.size() == 0 || k <= 0)
                {
                    break;
                }
                a.front() -= ac;                             
            }
        }
        cout << sunk << '\n';
    }
    return 0;
}
2024/4/10 23:09
加载中...