Daliy Algorithm (贪心)– day 72

Nothing to fear


种一棵树最好的时间是十年前,其次是现在!

那些你早出晚归付出的刻苦努力,你不想训练,当你觉的太累了但还是要咬牙坚持的时候,那就是在追逐梦想,不要在意终点有什么,要享受路途的过程,或许你不能成就梦想,但一定会有更伟大的事情随之而来。 mamba out~

2020.5.4


人一我十, 人十我百,追逐青春的梦想,怀着自信的心,永不言弃!

Make Product Equal One

贪心思想, 首先将问题过渡为一个更简单的问题,在进行求解时间复杂度O(n)

#ifdef LOCAL
#  define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <cassert>
#include <string>
#include <iomanip>
#include <cmath>
#include <ctime>
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define lowbit(x) (x & -x)
using namespace std;
typedef long long ll;
const int MAX = 0x7ffffff;
int t;

void slove()
{
    int n;
    cin >> n;
    vector<int> a(n);
    ll ans = 0;
    int ca = 0, cb = 0;
    for(int i = 0;i < n ;i ++) 
    {
        cin >> a[i];
        if(a[i] > 0)ans += a[i] - 1,a[i] = 1;
        if(a[i] < 0)ans +=-a[i] - 1,ca++,a[i] =-1;
        if(a[i] == 0)cb++;
    }
    if(ca % 2 == 0)ans += cb;
    else {
        if(cb == 0)ans += 2;
        else ans += cb;
    }
    cout << ans << endl;
}
int main()
{
#ifdef LOCAL
    auto start_time = clock();
    cerr << setprecision(3) << fixed;
#endif  
    SIS;
    slove();
#ifdef LOCAL
    auto end_time = clock();
    cerr << "Execution time: " << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << " ms\n";
#endif
}

原文链接: https://www.cnblogs.com/wlw-x/p/12828772.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Daliy Algorithm (贪心)-- day 72

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/346346

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午3:50
下一篇 2023年3月2日 上午3:51

相关推荐