1. 程式人生 > >【Codeforces 442B】Andrey and Problem

【Codeforces 442B】Andrey and Problem

print size ref put 改變 ioe run 思路 int

【鏈接】 我是鏈接,點我呀:)
【題意】


n個朋友
第i個朋友幫你的概率是pi
現在問你恰好有一個朋友幫你的概率最大是多少
前提是你可以選擇只問其中的某些朋友不用全問.

【題解】


主要思路是逆向思維,轉換成一個一個地加上去
然後看看概率的改變值在何時為正數,顯然只有為正數的時候才能加
然後概率大的和概率小的,哪一個加上去會比較優一點,也比較一下.
但是因為加上去之後S也會變化,所以只知道概率大的加上去比較優還不夠.
可以再看看下面那個反證法.
它指出為何一定是選擇末尾最大的若幹個(也即優先選擇p[i]最大的)
(反證的思想就是,假設i<j,但是p[i]在答案中,p[j]不在(p[i]< p[j]),那麽這個時候,如果我們把p[i]刪掉,再加上p[j]的話,顯然比原來相同數量的答案來的好)

(所以對於每一個不是選擇最大的若幹個概率的方案,我們總能讓這些方案更優一點
技術分享圖片

【代碼】

import java.io.*;
import java.util.*;

public class Main {
    
    
    static InputReader in;
    static PrintWriter out;
        
    public static void main(String[] args) throws IOException{
        //InputStream ins = new FileInputStream("E:\\rush.txt");
        InputStream ins = System.in;
        in = new InputReader(ins);
        out = new PrintWriter(System.out);
        //code start from here
        new Task().solve(in, out);
        out.close();
    }
    
    static int N = (int)100;
    static class Task{
        int n;
        double p[];
        double P=1,S,ans;
        
        public void solve(InputReader in,PrintWriter out) {
            p = new double[N+10];
            n = in.nextInt();
            for (int i = 1;i <= n;i++) p[i] = in.nextDouble();
            Arrays.sort(p, 1,1+n);
            if (Math.abs(p[n]-1)<(1e-9)) {
                out.println(1);
                return;
            }
            for (int i = n;i >= 1;i--) {
                if (S<1) {
                    P = P*(1-p[i]);
                    S = S + p[i]/(1-p[i]);
                    ans = P*S;
                }
            }
            out.println(ans);
        }
    }

    

    static class InputReader{
        public BufferedReader br;
        public StringTokenizer tokenizer;
        
        public InputReader(InputStream ins) {
            br = new BufferedReader(new InputStreamReader(ins));
            tokenizer = null;
        }
        
        public String next(){
            while (tokenizer==null || !tokenizer.hasMoreTokens()) {
                try {
                tokenizer = new StringTokenizer(br.readLine());
                }catch(IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
        
        public int nextInt() {
            return Integer.parseInt(next());
        }
        
        public double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}

【Codeforces 442B】Andrey and Problem