poj 3744 Scout YYF I(矩陣最佳化機率),pojyyf

來源:互聯網
上載者:User

poj 3744 Scout YYF I(矩陣最佳化機率),pojyyf

http://poj.org/problem?id=3744


有n個雷,某人的起始位置在1,每次走一步的機率為p,走兩步的機率是1-p,給出n個雷的位置,問最後成功走出雷區的機率。


放在高中應該是很簡單的分步乘法求機率。即把每一個雷都沒踩到的機率求出來,最後n個相乘就是順利通過的機率。對於輸入的n個位置進行分段1~num[1],num[1]+1~num[2]......每一段都只有一個雷num[i],每一段內踩不到雷的機率就是1-踩到num[i]雷的機率。

設dp[i]表示踩到第i個雷的機率,那麼dp[i] = p*dp[i-1] + (1-p)*dp[i-2],因為i較大,可以用矩陣相乘進行最佳化。


#include <stdio.h>#include <iostream>#include <map>#include <set>#include <list>#include <stack>#include <vector>#include <math.h>#include <string.h>#include <queue>#include <string>#include <stdlib.h>#include <algorithm>//#define LL __int64#define LL long long#define eps 1e-12#define PI acos(-1.0)using namespace std;const int INF = 0x3f3f3f3f;const int maxn = 4010;struct matrix{    double mat[2][2];    void init()    {        mat[0][0] = mat[1][1] = 1;        mat[0][1] = mat[1][0] = 0;    }}a,b,res;int num[15];int n;double p;matrix mul(matrix x, matrix y){    matrix t;    memset(t.mat,0,sizeof(t.mat));    for(int i = 0; i < 2; i++)    {        for(int k = 0; k < 2; k++)        {            if(x.mat[i][k] == 0) continue;            for(int j = 0; j < 2; j++)            {                t.mat[i][j] += x.mat[i][k]*y.mat[k][j];            }        }    }    return t;}matrix pow(matrix a, int n){    matrix t;    t.init();    while(n)    {        if(n&1)            t = mul(t,a);        n >>= 1;        a = mul(a,a);    }    return t;}int main(){    while(~scanf("%d %lf",&n,&p))    {        a.mat[0][0] = p;        a.mat[0][1] = 1-p;        a.mat[1][0] = 1;        a.mat[1][1] = 0;        memset(b.mat,0,sizeof(b.mat));        b.mat[0][0] = 1;        b.mat[1][0] = 0;        for(int i = 1; i <= n; i++)            scanf("%d",&num[i]);        sort(num+1,num+1+n);        double ans;        res = pow(a,num[1]-1);        res = mul(res,b);        ans = 1 - res.mat[0][0];        for(int i = 2; i <= n; i++)        {            res = pow(a,num[i]-num[i-1]-1);            res = mul(res,b);            ans *= (1-res.mat[0][0]);        }        printf("%.7f\n",ans);    }    return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.