[ACM] sdut 2878 Circle (高斯消元),sdut2878
CircleTime Limit: 2000ms Memory limit: 65536K 有疑問?點這裡^_^題目描述You have been given a circle from 0 to n - 1. If you are currently at x, you will move to (x - 1) mod n or (x + 1) mod n with equal probability. Now we want to know the expected number of steps you need to reach x from 0.輸入The first line contains one integer T — the number of test cases. Each of the next T lines contains two integers n, x (0 ≤ x < n ≤ 1000) as we mention above.輸出For each test case. Print a single float number — the expected number of steps you need to reach x from 0. The figure is accurate to 4 decimal places.樣本輸入
33 25 410 5
樣本輸出
2.00004.000025.0000
提示 來源2014年山東省第五屆ACM大學生程式設計競賽
解題思路:
題意為n個節點編號0到n-1,成一個環形,給定一個數x,求從0號節點走到x節點的期望步數是多少。節點向兩邊走的機率相同,每一步走一個節點。
高斯消元,n個方程,n個未知量, 設E[ p ] 為從p節點走到x節點還需要走的步數的期望數。那麼E [ x ] =0;
對於每個節點都有 E[p]=0.5*E[p-1]+0.5*E[p+1]+1, 即 -0.5*E[p-1]+E[p]-0.5*E[p+1]=1。
代碼:
#include <iostream>#include <cstdio>#include <cstring>#include <string.h>#include <cmath>#include <iomanip>#include <algorithm>using namespace std;///浮點型高斯消元模板const double eps=1e-12;const int maxm=1000;///m個方程,n個變數const int maxn=1000;int m,n;double a[maxm][maxn+1];///增廣矩陣bool free_x[maxn];///判斷是否是不確定的變元double x[maxn];///解集int sign(double x){ return (x>eps)-(x<-eps);}/**傳回值:-1 無解0 有且僅有一個解>=1 有多個解,根據free_x判斷哪些是不確定的解*/int Gauss(){ int i,j; int row,col,max_r; m=n;///n個方程,n個變數的那種情況 for(row=0,col=0;row<m&&col<n;row++,col++) { max_r=row; for(i=row+1;i<m;i++)///找到當前列所有行中的最大值(做除法時減小誤差) { if(sign(fabs(a[i][col])-fabs(a[max_r][col]))>0) max_r=i; } if(max_r!=row) { for(j=row;j<n+1;j++) swap(a[max_r][j],a[row][j]); } if(sign(a[row][col])==0)///當前列row行以下全為0(包括row行) { row--; continue; } for(i=row+1;i<m;i++) { if(sign(a[i][col])==0) continue; double tmp=a[i][col]/a[row][col]; for(j=col;j<n+1;j++) a[i][j]-=a[row][j]*tmp; } } for(i=row;i<m;i++)///col=n存在0...0,a的情況,無解 { if(sign(a[i][col])) return -1; } if(row<n)///存在0...0,0的情況,有多個解,自由變元個數為n-row個 { for(i=row-1;i>=0;i--) { int free_num=0;///自由變元的個數 int free_index;///自由變元的序號 for(j=0;j<n;j++) { if(sign(a[i][j])!=0&&free_x[j]) free_num++,free_index=j; } if(free_num>1) continue;///該行中的不確定的變元的個數超過1個,無法求解,它們仍然為不確定的變元 ///只有一個不確定的變元free_index,可以求解出該變元,且該變元是確定的 double tmp=a[i][n]; for(j=0;j<n;j++) { if(sign(a[i][j])!=0&&j!=free_index) tmp-=a[i][j]*x[j]; } x[free_index]=tmp/a[i][free_index]; free_x[free_index]=false; } return n-row; } ///有且僅有一個解,嚴格的上三角矩陣(n==m) for(i=n-1;i>=0;i--) { double tmp=a[i][n]; for(j=i+1;j<n;j++) if(sign(a[i][j])!=0) tmp-=a[i][j]*x[j]; x[i]=tmp/a[i][i]; } return 0;}///模板結束int t,xx;int main(){ cin>>t; while(t--) { cin>>n>>xx; memset(a,0,sizeof(a)); for(int i=0;i<n;i++) { if(i==xx) { a[i][i]=1; a[i][n]=0; continue; } a[i][i]=1; a[i][n]=1; a[i][(i-1+n)%n]=-0.5; a[i][(i+1)%n]=-0.5; } Gauss(); cout<<setiosflags(ios::fixed)<<setprecision(4)<<x[0]<<endl; } return 0;}