zoukankan      html  css  js  c++  java
  • AtCoder Beginner Contest 173E Multiplication 4(思维)

    题意:给出长度为n的序列a,选出k个数字使得连乘积最大,输出取模mod。n<2e5,a[i]<1e9

    题解:从小到大排序,k为奇数先取一个最大的,之后就是比较开头两个的乘积和结尾两个乘积的大小,注意当k为奇数的时候,且a全部为负数的时候分开讨论一下,还有就是需要先取模再乘积,会爆long long

    #include <bits/stdc++.h>
    #define IOS ios::sync_with_stdio(false);cin.tie(0)
    #define fre freopen("C:\in.txt", "r", stdin)
    #define _for(i,a,b) for(int i=a; i< b; i++)
    #define _rep(i,a,b) for(int i=a; i<=b; i++)
    #define lowbit(a) ((a)&-(a))
    #define inf 0x3f3f3f3f
    #define endl "
    "
    using namespace std;
    typedef long long ll;
    template <class T>
    void read(T &x)
    {
        char c; bool op=0;
        while(c=getchar(), c<'0'||c>'9') if(c=='-') op=1;
        x=c-'0';
        while(c=getchar(), c>='0'&&c<='9') x=x*10+c-'0';
        if(op) x=-x;
    }
    
    const int mod=1e9+7;
    
    int main()
    {
        int n, k;
        read(n), read(k);
        vector<ll> a(n);
        for(auto &val: a) read(val);
        sort(a.begin(), a.end());
        ll ans=1; int ok=0;
        if(k%2) ans*=a[--n], k--;
        if(ans<0) ok=1;
        int l=0, r=n-1;
        while(k){
            ll x=a[r]*a[r-1], y=a[l]*a[l+1];
            if(ok || x>y)
                ans=x%mod*ans%mod, r-=2; //注意每次取余,会溢出long long
            else ans=y%mod*ans%mod, l+=2;
            //cout<<l<<" "<<r<<" "<<ans<<endl;
            k-=2;
        }
        printf("%lld
    ", (ans+mod)%mod);
        return 0;
    }
  • 相关阅读:
    WPF基础篇之控件模板(ControlTemplate)
    WPF基础篇之移动特效
    WPF基础篇之空间布局
    00-API-Mongoose
    00-API-Vue
    博客园皮肤设置
    15-Node
    16-Vue-A
    15-MongoDB
    14-电商项目
  • 原文地址:https://www.cnblogs.com/Yokel062/p/13456578.html
Copyright © 2011-2022 走看看