CodeForces Gym 100685E Epic Fail of a Genie (贪心,控制精度)

题意:给定 n 个数,然后让从中选取一些数使得它们的总乘积最大。如果有多个,要求这些数尽量少,如果还有多个,随便输出一组即可。

析:一个贪心题,根据乘法的性质,很容易知道,如果一个数大于1,那么肯定要选的,然后如果有两个负数乘积大于1,也要选上,其他的尽量不要选。

最后如果没有这样数,那么就只要计算最小的两个数乘积与最大的比较即可,主要是因为是最小的两个可能是负数,如果不是也不影响结果。

这个题在比赛时,竟然没有AC,。。。主要原因是我没有控制精度,卡了好久,如果控制一下精度就AC了,可以把所有的实数都乘以100,然后再计算。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e4 + 5;
const int mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline int Min(int a, int b){ return a < b ? a : b; }
inline int Max(int a, int b){ return a > b ? a : b; }
inline LL Min(LL a, LL b){ return a < b ? a : b; }
inline LL Max(LL a, LL b){ return a > b ? a : b; }
inline bool is_in(int r, int c){
    return r >= 0 && r < n && c >= 0 && c < m;
}
struct node{
    int id;
    LL val;
    bool operator < (const node &p) const{
        return val < p.val;
    }
};
node a[maxn];
vector<int> ans;

int main(){
    while(scanf("%d", &n) == 1){
        double x;
        for(int i = 0; i < n; ++i){
            scanf("%lf", &x);
            a[i].val = x * 100.0;
            a[i].id = i+1;
        }
        sort(a, a+n);
        ans.clear();
        int cnt = 0;
        for(int i = 0; i < n; ++i){
            if(a[i].val < -100LL){
                if(i+1 < n && a[i].val * a[i+1].val > 10000LL){
                        ans.push_back(a[i].id), ans.push_back(a[i+1].id), ++i;
                }
            }
            else if(a[i].val > 100LL)  ans.push_back(a[i].id);
        }

        if(ans.empty()){
            LL s = a[0].val * a[1].val;
            if(s > a[n-1].val * 100LL)  ans.push_back(a[0].id), ans.push_back(a[1].id);
            else  ans.push_back(a[n-1].id);
        }
        printf("%d
", ans.size());
        sort(ans.begin(), ans.end());
        for(int i = 0; i < ans.size(); ++i){
            if(i)  putchar(' ');
            printf("%d", ans[i]);
        }
        printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/5825700.html