Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <algorithm> #include <cstdio> #include <cmath> #include <map> #include <vector> using namespace std; const int MOD = 256; const double EPS = 1e-7; const int INF = 1<<29; int n,I[257],R[257],O[257]; vector<int> sharp; bool equal(double a, double b){ return fabs(a-b) < EPS; } void makeR(int S, int A, int C){ R[0] = S; for(int i=1;i<=n;i++){ R[i] = (A * R[i-1] + C) % MOD; } } void makeO(){ map<int,int> mp; sharp.clear(); for(int i=1;i<=n;i++){ O[i] = (I[i] + R[i]) % MOD; if(mp.find(O[i]) == mp.end()) mp[O[i]] = 1; else mp[O[i]]++; } for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++) sharp.push_back(it->second); } double calcH(){ double H = 0, N = (double)n; for(int i=0;i<sharp.size();i++){ double x = (double)sharp[i]; H += (x / N) * log(x / N); } return H * -1.0; } void solve(){ vector<int> sharp; double H, ans = (double)INF; int sum = INF, as, aa, ac; for(int S=0;S<=15;S++){ for(int A=0;A<=15;A++){ for(int C=0;C<=15;C++){ makeR(S,A,C); makeO(); H = calcH(); if(ans > H && !equal(ans,H) /*|| equal(ans,H) && sum > S+A+C*/){ ans = H; sum = S+A+C; as = S; aa = A; ac = C; } } } } cout << as << ' ' << aa << ' ' << ac << endl; } int main(){ while(cin >> n && n){ for(int i=1;i<=n;i++){ cin >> I[i]; } solve(); } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <math.h> #include <vector> using namespace std; #define rep(i, e) for( int i = 0; i < e; i++ ) #define eps 1e-10 typedef vector<int> vec; int main(){ int N, M = 256; while( cin >> N, N){ vec I(N); rep(i, N) cin >> I[i]; int S, A, C; double H = 1000000; rep(s, 16){ rep(a, 16){ rep(c, 16){ int R = s, O, x[256] = {0}; //O[0] = ( I[0] + R[0] ) % M; double h = 0;//-( O[0] / N ) * log(O[0] / N); rep(i, N){ R = (a*R+c) % M; O = (I[i] + R) % M; x[O]++; } rep(i, M){ if( !x[i] ) continue; double t = 1.0 * x[i] / N; h -= (t * log(t)); } if( h+eps < H ){ H = h; S = s; A = a; C = c; //cout << H << ' ' << s << ' ' << a << ' ' << c << endl; } } } } cout << S << ' ' << A << ' ' << C << endl; } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <bits/stdc++.h> using namespace std; #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) typedef long double Double; int main() { typedef pair<int, int> Pii; typedef pair<int, Pii> Piii; int N; int const M = 256; while(cin >> N && N) { vector<int> I(N); rep(i, N) cin >> I[i]; Double Entropy = 1e60; Piii ans; rep(S, 16) rep(A, 16) rep(C, 16) { int numofx[256] = {}; int R = S; rep(i, N) { R = (A*R+C) % M; numofx[ (I[i]+R)%M ] ++; } Double H = 0.; rep(i, M) { if(numofx[i]) { Double x = (Double)numofx[i] / N; H -= x * log(x); } } if(H < Entropy-1e-9) { Entropy = H; ans = Piii(S, Pii(A, C)); } else if(H == Entropy) { ans = min(ans, Piii(S, Pii(A, C))); } } cout << ans.first << " " << ans.second.first << " " << ans.second.second << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; typedef long double elm; const elm inf = 1e100; const int M = 256; int N; vector<int> I; int cnt[M]; elm test(int s, int a, int c) { fill(cnt, cnt+M, 0); int r = s; for(int i = 0; i < N; ++i) { r = (a*r+c) % M; int o = (I[i] + r) % M; ++cnt[o]; } elm res = 0; for(int i = 0; i < M; ++i) { if(cnt[i]) { res += cnt[i] * (log(cnt[i]) - log(N)); } } return -res; } int main() { while(cin >> N && N) { I.resize(N); for(int i = 0; i < N; ++i) { long long s; cin >> s; I[i] = s % M; } elm mini = inf; int S, A, C; for(int s = 0; s <= 15; ++s) { for(int a = 0; a <= 15; ++a) { for(int c = 0; c <= 15; ++c) { elm h = test(s,a,c); if(h < mini) { mini = h; S = s; A = a; C = c; } } } } cout << S << " " << A << " " << C << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<stdio.h> #include <iostream> #include <math.h> #include <numeric> #include <vector> #include <map> #include <functional> #include <stdio.h> #include <array> #include <algorithm> #include <string> #include <string.h> #include <assert.h> #include <stdio.h> #include <queue> #include<iomanip> #include<bitset> #include<stack> #include<set> #include<limits> #include <complex> #include<cstdlib> using namespace std; #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(),(x).end() pair<long long int,int> getans(long long int a) { if (a == 0) { return make_pair(0, 0); } else if (a == 1) { return make_pair(1, 0); } } int main() { while (1) { int n; cin >> n; if (!n)break; vector<int>ls; for (int i = 0; i < n; ++i) { int l; cin >> l; ls.push_back(l); } long double maxH =999999999; int anss, ansa, ansc; for (int s = 0; s < 16; ++s) { for (int a = 0; a < 16; ++a) { for (int c = 0; c < 16; ++c) { vector<int>rs(n+1); rs[0] = s; for (int i = 0; i < n; ++i) { rs[i + 1] = (rs[i] * a + c) % 256; } long double H = 0; vector<int>os(256); for (int i = 0; i < n; ++i) { os[(ls[i] + rs[i+1]) % 256]+=1 ; } for (int i = 0; i < 256; ++i) { if (os[i]) H -= os[i] / static_cast<long double>(n) * log(os[i] / static_cast<long double>(n)); } if (H < maxH-0.00000001) { maxH = H; anss = s; ansa = a; ansc = c; } } } } cout << anss << " " << ansa << " " << ansc << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<iostream> #include<math.h> #define MOD 256 using namespace std; int main(){ int n; int i,j,k,l; int s,a,c,bs,ba,bc; int r[16][16][16][260]; for(s=0;s<16;s++){ for(a=0;a<16;a++){ for(c=0;c<16;c++){ r[s][a][c][0]=s; for(i=0;i<260-1;i++){ r[s][a][c][i+1]=(a*r[s][a][c][i]+c)%MOD; } } } } cin >> n; while(n!=0){ int inf = 1 << 5; double m=inf,o=0; int ma[260]={}; for(i=0;i<n;i++) cin >> ma[i]; float co[260]={}; for(s=0;s<16;s++){ for(a=0;a<16;a++){ for(c=0;c<16;c++){ o=0; for(i=0;i<260;i++) co[i]=0; for(i=0;i<n;i++){ k=(ma[i]+r[s][a][c][i+1])%MOD; co[k]+=1;; } for(i=0;i<260;i++){ if(co[i]!=0){ o-=(co[i]/n)*log(co[i]/n); //cout << i <<" "<<co[i]<< endl; } } if(m>o){ m=o; bs=s;ba=a;bc=c; } } } } cout << bs << " " << ba << " " << bc << endl; cin >> n; } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) int cnt[300]; int input[300]; int main() { int n; while (scanf("%d", &n), n) { REP(i, n) { scanf("%d", &input[i]); } double ansmin = 1e+10; int anss, ansa, ansc; REP(s, 16) REP(a, 16) REP(c, 16) { MEMSET(cnt, 0); int r = s; REP(i, n) { r = (a * r + c) % 256; int o = (r + input[i]) % 256; cnt[o]++; } double h = 0.0; REP(i, 256) { if (cnt[i] == 0) { continue; } h -= cnt[i] / (double)n * log(cnt[i] / (double)n); } if (h - ansmin < -EPS) { ansmin = h; anss = s; ansa = a; ansc = c; } } printf("%d %d %d\n", anss, ansa, ansc); } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<iostream> #include<cmath> #include<vector> using namespace std; int R[16][16][16][256]={0}; int main(){ for(int S=0;S<=15;S++){ for(int A=0;A<=15;A++){ for(int C=0;C<=15;C++){ R[S][A][C][0]=S; for(int i=1;i<256;i++){ R[S][A][C][i]=(A*R[S][A][C][i-1]+C)%256; } } } } int n; while(cin>>n,n){ vector<int> v(n); for(int i=0;i<n;i++){ cin>>v[i]; } int s=0,a=0,c=0; double mi=1000000; for(int S=0;S<=15;S++){ for(int A=0;A<=15;A++){ for(int C=0;C<=15;C++){ int table[256]={0}; for(int i=0;i<n;i++){ table[(v[i]+R[S][A][C][i+1])%256]++; } double h=0.0; for(int i=0;i<256;i++){ if(table[i]){ double t=(double)table[i]/n; h+=(t*log(t)); } } h=-h; if((mi-h) > 1e-6){ mi=h; s=S; a=A; c=C; } } } } cout<<s<<" "<<a<<" "<<c<<endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <utility> #include <cstring> #include <cmath> const double EPS = 1e-9; const int INF = 10000000; const int MOD = 1e9 + 7; const int dx[] = {1, -1, 0, 0}; const int dy[] = {0, 0, 1, -1}; typedef long long ll; using namespace std; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; while(cin >> n, n) { vector<int> vec(n + 1), R(n + 1), O(n + 1); for(int i = 0; i < n; i++) { cin >> vec[i]; } double H = 1e9; int ans1, ans2, ans3; for(int s = 0; s < 16; s++) { for(int a = 0; a < 16; a++) { for(int c = 0; c < 16; c++) { vector<int> cnt(256, 0); R[0] = s; for(int i = 1; i <= n; i++) { R[i] = (a * R[i - 1] + c) % 256; O[i] = (vec[i - 1] + R[i]) % 256; cnt[O[i]]++; } double sum = 0; for(int i = 0; i < 256; i++) { if(cnt[i] <= 0) continue; sum -= (((double)cnt[i] / n) * log((double)cnt[i] / n)); } if(sum + EPS < H) { H = sum; ans1 = s; ans2 = a; ans3 = c; } } } } cout << ans1 << " " << ans2 << " " << ans3 << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <vector> #include <map> #include <cmath> using namespace std; const int MAX_N = 256; const int M = 256; int N, S, A, C; int I[MAX_N + 10], R[MAX_N + 10], O[MAX_N + 10]; int main() { while (cin >> N, N) { for (int i = 1; i <= N; ++i) cin >> I[i]; S = A = C = 16; double H = 1e9; for (int s = 0; s <= 15; ++s) { for (int a = 0; a <= 15; ++a) { for (int c = 0; c <= 15; ++c) { R[0] = s; map<int, int> x; for (int i = 1; i <= N; ++i) { R[i] = (a * R[i - 1] + c) % M; O[i] = (I[i] + R[i]) % M; if (x.count(O[i]) == 0) { x.insert(map<int, int>::value_type(O[i], 1)); } else x[O[i]]++; } double h = 0; map<int, int>::iterator it = x.begin(); while (it != x.end()) { h -= (*it).second * log((*it).second); ++it; } if (h + 1e-9 < H) { H = h; S = s; A = a; C = c; } } } } cout << S << " " << A << " " << C << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<iostream> #include<cstring> #include<map> #include<cmath> #include<vector> using namespace std; #define EPS 1e-10 double entropy(int s,int a,int c,vector<int> v){ map<int,int> mp; for(int i=0;i<v.size();i++){ s = (a*s+c)&255; ++mp[(s+v[i])&255]; } map<int,int>::iterator it; double res=0,n=v.size(); for(it=mp.begin();it!=mp.end();++it){ res -= it->second/n*log(it->second/n); } return res; } int main(){ int n; while(cin>>n&&n){ vector<int> v(n); for(int i=0;i<n;i++)cin>>v[i]; double maxe=1e10; int anss,ansa,ansc; for(int s=0;s<=15;s++){ for(int a=0;a<=15;a++){ for(int c=0;c<=15;c++){ double e=entropy(s,a,c,v); if(e+EPS<maxe){ maxe=e; anss=s; ansa=a; ansc=c; } } } } cout<<anss<<' '<<ansa<<' '<<ansc<<endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<iostream> #include<cstring> #include<cmath> #include<vector> using namespace std; #define EPS 1e-10 double entropy(int s,int a,int c,vector<int> v){ int freq[256]={}; for(int i=0;i<v.size();i++){ s = (a*s+c)&255; freq[(s+v[i])&255]++; } double res=0,n=v.size(); for(int i=0;i<256;i++){ if(!freq[i])continue; res -= freq[i]/n*log(freq[i]/n); } return res; } int main(){ int n; while(cin>>n&&n){ vector<int> v(n); for(int i=0;i<n;i++)cin>>v[i]; double maxe=1e10; int anss,ansa,ansc; for(int s=0;s<=15;s++){ for(int a=0;a<=15;a++){ for(int c=0;c<=15;c++){ double e=entropy(s,a,c,v); if(e+EPS<maxe){ maxe=e; anss=s; ansa=a; ansc=c; } } } } cout<<anss<<' '<<ansa<<' '<<ansc<<endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<iostream> #include<cmath> #include<algorithm> using namespace std; int main(){ int n,l[300],u[300]; while(cin >> n,n){ for(int i=0;i<n;i++)cin >> l[i]; double m = 1e10; int x,y,z; for(int s=0;s<16;s++){ for(int a=0;a<16;a++){ for(int c=0;c<16;c++){ for(int i=0;i<256;i++)u[i] = 0; int r = s; for(int i=0;i<n;i++){ r = (a*r + c) % 256; u[(r + l[i]) % 256]++; } double tmp = 0; for(int i=0;i<256;i++)if(u[i])tmp -= (double)u[i]*log((double)u[i]/n); if(m > tmp + 1e-8){ m = tmp; x = s; y = a; z = c; } } } } cout << x << " " << y << " " << z << endl; } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<bits/stdc++.h> #define INF 1e9 #define llINF 1e18 #define MOD 1000000007 #define pb push_back #define mp make_pair #define F first #define S second #define ll long long #define vi vector<ll> #define vvi vector<vi> #define BITLE(n) (1LL<<((ll)n)) #define SHIFT_LEFT(n) (1LL<<((ll)n)) #define SUBS(s,f,t) ((s).substr((f)-1,(t)-(f)+1)) #define ALL(a) (a).begin(),(a).end() #define EPS 1e-15 using namespace std; double calc(vi L,vi R){ map<ll,ll>cnt; ll n = L.size(); for(int i=0;i<n;i++){ cnt[(L[i]+R[i+1])%256]++; } double ret = 0; for(auto a:cnt){ ret += (double)((double)a.S/n)*log((double)a.S/n); } return -ret; } int main(){ cin.tie(0); ios::sync_with_stdio(false); ll n; while(cin>>n,n){ vi A(n); for(auto &a:A)cin>>a; vi R(n+1); double mi = llINF; ll as = 0,aa = 0,ac = 0; for(ll s = 0;s <= 15;s++){ for(ll a = 0;a <= 15;a++){ for(ll c = 0;c <= 15;c++){ R[0] = s; for(int i=1;i<=n;i++){ R[i] = (a*R[i-1]+c)%256; } double entropy = calc(A,R); if(mi - entropy <= EPS){ /* cout<<"!"<<endl; cout<<as<<" "<<aa<<" "<<ac<<endl; cout<<s<<" "<<a<<" "<<c<<endl; */ if(as > s){ as = s;aa = a;ac = c; }else if(as == s){ if(aa > a){ as = s;aa = a;ac = c; }else if(aa == a){ if(ac > c){ as = s;aa = a;ac = c; } } } }else if(entropy < mi){ mi = entropy; as = s;aa = a;ac = c; } // if(s == 0 && a == 4 && c == 3){ // cout<<entropy<<" "<<s<<a<<c<<endl; // } // if(s == 0 && a == 11 && c == 5){ // cout<<entropy<<" "<<s<<a<<c<<endl; // } } } } cout<<as<<" "<<aa<<" "<<ac<<endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <cmath> using namespace std; int main() { ios::sync_with_stdio(false); const int M = 256; int N; while (cin >> N && N) { int I[256]; for (int i=1; i<=N; ++i) cin >> I[i]; double Hmin = 1000.0; int s, a, c, upper = N; for (int S=0; S<=15; ++S) { for (int A=0; A<=15; ++A) { for (int C=0; C<=15; ++C) { int x[256] = {0}; int R = S; int O; int cnt = 0; for (int i=1; i<=N; ++i) { R = (A * R + C) % M; O = (I[i] + R) % M; cnt += x[O] == 0; if (upper < cnt) break; x[O] ++; } if (cnt <= upper) { upper = cnt; double H = 0; for (int i=0; i<256; ++i) { if (x[i]) H -= (double)x[i] / N * log((double)x[i] / N); } if (H + 1e-9 < Hmin) { Hmin = H; s = S; a = A; c = C; } } } } } cout << s << " " << a << " " << c << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <string> #include <vector> #include <cmath> using namespace std; double entropy(int N, const vector<int> &x) { double H = 0; for (int i=0; i<256; ++i) { if (x[i] != 0) { H -= (double)x[i] / N * log((double)x[i] / N); } } return H; } int main() { ios::sync_with_stdio(false); int N; while (cin >> N && N) { vector<int> I(N+1); for (int i=1; i<=N; ++i) cin >> I[i]; int M = 256; double Hmin = 100000.0; vector<int> ans(3); for (int S=0; S<=15; ++S) { for (int A=0; A<=15; ++A) { for (int C=0; C<=15; ++C) { vector<int> x(256, 0); int R = S; int O; int cnt = 0; int upper = N; for (int i=1; i<=N; ++i) { R = (A * R + C) % M; O = (I[i] + R) % M; cnt += x[O] == 0; if (upper < cnt) break; x[O] ++; } if (upper < cnt) continue; upper = cnt; double H = entropy(N, x); if (H + 1e-8 < Hmin) { Hmin = H; ans[0] = S; ans[1] = A; ans[2] = C; } } } } cout << ans[0] << " " << ans[1] << " " << ans[2] << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <cstdio> #include <vector> #include <set> #include <map> #include <queue> #include <deque> #include <stack> #include <algorithm> #include <cstring> #include <functional> #include <cmath> using namespace std; #define rep(i,n) for(int i=0;i<(n);++i) #define rep1(i,n) for(int i=1;i<=(n);++i) #define all(c) (c).begin(),(c).end() #define fs first #define sc second #define pb push_back #define show(x) cout << #x << " " << x << endl double eps=1e-9; int main(){ while(true){ int N,a[256],R[257],cnt[256]; cin>>N; if(N==0) break; rep(i,N) cin>>a[i]; double mx=1e10; int ss,aa,cc; rep(S,16) rep(A,16) rep(C,16){ R[0]=S; rep(i,N) R[i+1]=(A*R[i]+C)%256; rep1(i,N) R[i]=(R[i]+a[i-1])%256; double H=0; rep(i,256) cnt[i]=0; rep1(i,N) cnt[R[i]]++; rep(i,256){ if(cnt[i]>0){ H-=(double)cnt[i]/N*log((double)cnt[i]/N); } } if(H<mx-eps) mx=H,ss=S,aa=A,cc=C; } cout<<ss<<" "<<aa<<" "<<cc<<endl; } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include "bits/stdc++.h" using namespace std; //#define int long long #define DBG 1 #define dump(o) if(DBG){cerr<<#o<<" "<<(o)<<" ";} #define dumpl(o) if(DBG){cerr<<#o<<" "<<(o)<<endl;} #define dumpc(o) if(DBG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;} #define rep(i,a,b) for(int i=(a);i<(b);i++) #define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--) #define all(c) begin(c),end(c) const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f; const int MOD = (int)(1e9 + 7); template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template<class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } signed main() { cout << fixed << setprecision(10); int M = 256; for (int N; cin >> N&&N;) { vector<int> I(N + 1); rep(i, 1, N + 1) { cin >> I[i]; } vector<int> R(N + 1); double minH = INF; int ansS, ansA, ansC; rep(S, 0, 16)rep(A, 0, 16)rep(C, 0, 16) { R[0] = S; vector<int> cnt(256, 0); rep(i, 1, N + 1) { R[i] = (A*R[i - 1] + C) % M; int O = (I[i] + R[i]) % M; cnt[O]++; } double H = 0; rep(i, 0, 256) { if (cnt[i] == 0)continue; H += -cnt[i] * log((double)cnt[i] / N); } if (minH > H + 1e-9) { minH = H; ansS = S, ansA = A, ansC = C; } } cout << ansS << " " << ansA << " " << ansC << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <cstdio> #include <cstring> #include <cmath> #define mod 256 int n; int l[258]; int r[16][16][16][258]; int cnt[258]; int main(void){ for(int s=0;s<=15;s++){ for(int a=0;a<=15;a++){ for(int c=0;c<=15;c++){ r[s][a][c][0]=s; for(int q=1;q<=256;q++){ r[s][a][c][q]=(a*r[s][a][c][q-1]+c)%mod; } } } } while(1){ scanf("%d",&n); if(n==0)break; for(int i=1;i<=n;i++){ scanf("%d",&l[i]); } double res=0.0; int rs=-1,ra,rc; for(int s=0;s<=15;s++){ for(int a=0;a<=15;a++){ for(int c=0;c<=15;c++){ memset(cnt,0,sizeof(cnt)); for(int q=1;q<=n;q++){ cnt[(r[s][a][c][q]+l[q])%mod]++; } double val=0.0; for(int i=0;i<=255;i++){ if(cnt[i]==0)continue; val-=(double)cnt[i]*log((double)cnt[i]); } if(val<res || rs==-1){ rs=s; ra=a; rc=c; res=val; } } } } printf("%d %d %d\n",rs,ra,rc); } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <vector> #include <cmath> #include <cstring> using namespace std; const int M = 256; int x[256]; double entropy(int N) { double H = 0; for (int i=0; i<256; ++i) { if (x[i] != 0) { H -= (double)x[i] / N * log((double)x[i] / N); } } return H; } int main() { ios::sync_with_stdio(false); int N; while (cin >> N && N) { vector<int> I(N+1); for (int i=1; i<=N; ++i) cin >> I[i]; double Hmin = 100000.0; vector<int> ans(3); int upper = N; for (int S=0; S<=15; ++S) { for (int A=0; A<=15; ++A) { for (int C=0; C<=15; ++C) { memset(x, 0, sizeof x); int R = S; int O; int cnt = 0; for (int i=1; i<=N; ++i) { R = (A * R + C) % M; O = (I[i] + R) % M; cnt += x[O] == 0; if (upper < cnt) break; x[O] ++; } if (upper < cnt) continue; upper = cnt; double H = entropy(N); if (H + 1e-8 < Hmin) { Hmin = H; ans[0] = S; ans[1] = A; ans[2] = C; } } } } cout << ans[0] << " " << ans[1] << " " << ans[2] << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <stdio.h> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <vector> typedef long long int ll; #define BIG_NUM 2000000000 using namespace std; int N; void func(){ double minimum = (double)BIG_NUM,tmp; int ans_S,ans_A,ans_C,M=256,R[N+1],input[N+1],O[N+1],check[256]; for(int i = 1; i <= N; i++)scanf("%d",&input[i]); for(int s = 0; s <= 15; s++){ for(int a = 0; a <= 15; a++){ for(int c = 0; c <= 15; c++){ R[0] = s; for(int i = 1; i <= N; i++){ R[i] = (a*R[i-1]+c)%M; } for(int i = 0; i <= 255; i++)check[i] = 0; for(int i = 1; i <= N; i++){ O[i] = (input[i]+R[i])%M; check[O[i]]++; } tmp = 0.0; for(int i = 0; i <= 255; i++){ if(check[i] == 0)continue; tmp += (double)-1*((double)check[i]/(double)N)*log((double)check[i]/(double)N); } if(minimum - tmp > 0.0000000001){ minimum = tmp; ans_S = s; ans_A = a; ans_C = c; } } } } printf("%d %d %d\n",ans_S,ans_A,ans_C); } int main(){ while(true){ scanf("%d",&N); if(N == 0)break; func(); } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <vector> #include <string> #include <math.h> using namespace std; int main() { while( true ) { long long int n; cin >> n; if ( n == 0 ) break; vector< long long int > v; for ( long long int i = 0; i < n; i++ ) { long long int in; cin >> in; v.push_back( in ); } double ans; long long int ans_s = -1, ans_a, ans_c; for ( long long int s = 0; s <= 15; s++ ) { for ( long long int a = 0; a <= 15; a++ ) { for ( long long int c = 0; c <= 15; c++ ) { long long int r = s; long long int x[256] = {}; for ( long long int i = 0; i < n; i++ ) { r = ( a * r + c ) % 256; long long int o = ( v[i] + r ) % 256; x[o]++; } double h = 0.00; for ( long long int i = 0; i < 256; i++ ) { if ( x[i] == 0 ) continue; double b = 1.00 * x[i] / n; h -= b * log( b ); } if ( ans_s == -1 || ans - h > 1e-10 ) { ans = h; ans_s = s; ans_a = a; ans_c = c; } } } } cout << ans_s << " " << ans_a << " " << ans_c << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<bits/stdc++.h> #define M 256 #define EPS 1e-9 using namespace std; int n,R[M],I[M],O,x[M]; double ans; int ansS,ansA,ansC; void ROcalc(int S,int A,int C){ R[0]=S; for(int i=1;i<=n;i++) R[i]=(A*R[i-1]+C)%M,O=(I[i]+R[i])%M,x[O]++; } void Hcalc(int S,int A,int C){ double H=0; for(int i=0;i<M;i++)if(x[i]>0)H-=((double)x[i]/n)*(log((double)x[i]/n)); if(ans>H+EPS) ans=H,ansS=S,ansA=A,ansC=C; } int main(){ while(1){ cin>>n; ans=M; if(n==0) break; for(int i=1;i<=n;i++)cin>>I[i]; for(int i=0;i<=15;i++) for(int j=0;j<=15;j++) for(int k=0;k<=15;k++)memset(x,0,sizeof(x)),ROcalc(i,j,k),Hcalc(i,j,k); cout<<ansS<<" "<<ansA<<" "<<ansC<<endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
//#define __USE_MINGW_ANSI_STDIO 0 #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<ll> VL; typedef vector<VL> VVL; typedef pair<int, int> PII; #define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i) #define REP(i, n) FOR(i, 0, n) #define ALL(x) x.begin(), x.end() #define MP make_pair #define PB push_back #define MOD 1000000007 #define INF (1LL<<30) #define LLINF (1LL<<60) #define PI 3.14159265359 #define EPS 1e-9 //#define int ll int l[300], r[300], o[300], cnt[300]; signed main(void) { while(true) { int n; cin >> n; if(!n) break; REP(i, n) cin >> l[i]; int ss = -1, aa = -1, cc = -1; double mi = 1e9; REP(s, 16) REP(a, 16) REP(c, 16) { r[0] = s; REP(i, 256) cnt[i] = 0; FOR(i, 1, n+1) { r[i] = (a*r[i-1]+c) % 256; cnt[(l[i-1]+r[i])%256]++; } double ent = 0; REP(i, 256) { if(cnt[i] != 0) ent -= (cnt[i] / (double)(n) * log(cnt[i] / (double)(n))); } if(ent+EPS < mi) { mi = ent; ss = s; aa = a; cc = c; } } cout << ss << " " << aa << " " << cc << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <climits> #include <cmath> #include <cstdlib> #include <iostream> #include <map> #include <vector> using namespace std; #define FOR(it,c) for(__typeof((c).begin())it=(c).begin(); it!=(c).end();++it) int main() { cin.tie(0); ios::sync_with_stdio(false); const int mod = 256; for(int n; cin >> n, n;) { vector<int> l(n); for(int i = 0; i < n; ++i) cin >> l[i]; int as, aa, ac; double mn = INT_MAX; for(int s = 0; s <= 15; ++s) { for(int a = 0; a <= 15; ++a) { for(int c = 0; c <= 15; ++c) { int r = s; map<int, int> cnt; for(int i = 0; i < n; ++i) { r = (a * r + c) % mod; ++cnt[(l[i] + r) % mod]; } double h = 0.0; FOR(it, cnt) { const double tmp = (double)it->second / n; h -= tmp * log2(tmp); } if(mn > h) { as = s; aa = a; ac = c; mn = h; } } } } cout << as << " " << aa << " " << ac << endl; } return EXIT_SUCCESS; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <cmath> #include <iostream> using namespace std; int n, a[256]; int main() { while (cin >> n, n) { for (int i = 0; i < n; i++) cin >> a[i]; int mi, mj, mk; double v = 1e+300; for (int i = 0; i < 16; i++) { for (int j = 0; j < 16; j++) { for (int k = 0; k < 16; k++) { int b[257] = { 0 }, c[257] = { 0 }; b[0] = i; for (int l = 1; l <= n; l++) b[l] = (j * b[l - 1] + k) % 256; for (int l = 0; l < n; l++) c[(a[l] + b[l + 1]) % 256]++; double res = 0; for (int l = 0; l < 256; l++) { if (c[l]) res -= c[l] * log(1.0 * c[l] / n); } if (v - 1e-9 > res) v = res, mi = i, mj = j, mk = k; } } } cout << mi << ' ' << mj << ' ' << mk << endl; } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<cmath> #include<cstdio> #define rep(i,n) for(int i=0;i<n;i++) using namespace std; const double EPS=1e-9; int main(){ const int M=256; for(int N;scanf("%d",&N),N;){ int I[257]; for(int i=1;i<=N;i++) scanf("%d",I+i); int Smin,Amin,Cmin; double Hmin=1e30; rep(S,16)rep(A,16)rep(C,16){ int R[257]; R[0]=S; for(int i=1;i<=N;i++) R[i]=(A*R[i-1]+C)%M; int O[256]={}; for(int i=1;i<=N;i++) O[(I[i]+R[i])%M]++; double H=0; rep(i,M) if(O[i]>0) H-=1.*O[i]/N*log(1.*O[i]/N); if(H<Hmin-EPS){ Hmin=H; Smin=S,Amin=A,Cmin=C; } } printf("%d %d %d\n",Smin,Amin,Cmin); } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <algorithm> #include <numeric> #include <vector> #include <cassert> #include <string> #include <memory.h> #include <queue> #include <cstdio> #include <cstdlib> #include <set> #include <map> #include <cctype> #include <iomanip> #include <sstream> #include <cctype> #include <fstream> #include <cmath> using namespace std; #define REP2(i, m, n) for(int i = (int)(m); i < (int)(n); i++) #define REP(i, n) REP2(i, 0, n) #define ALL(c) (c).begin(), (c).end() #define ITER(c) __typeof((c).begin()) #define PB(e) push_back(e) #define FOREACH(i, c) for(ITER(c) i = (c).begin(); i != (c).end(); ++i) #define MP(a, b) make_pair(a, b) #define PARITY(n) ((n) & 1) typedef long long ll; typedef pair<ll, ll> P; const int INF = 1000 * 1000 * 1000 + 7; const double EPS = 1e-10; int main(){ int N; const int M = 256; while(cin >> N && N){ vector<int> L(N); REP(i, N) cin >> L[i]; int bestS = 0, bestA = 0, bestC = 0; double best = 1e20; REP(S, 16)REP(A, 16)REP(C, 16){ vector<int> R(N + 1); vector<int> O(N); R[0] = S; REP(i, N) R[i+1] = (A * R[i] + C) % M; map<int, int> count; REP(i, N) count[(L[i] + R[i+1]) % M]++; double h = 0; FOREACH(it, count){ double p = (double)(it->second) / N; h -= p * log(p); } if(h < best - EPS){ best = h; bestS = S; bestA = A; bestC = C; } } cout << bestS << " " << bestA << " " << bestC << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <bits/stdc++.h> using namespace std; const int MAX=256; const double EPS=1e-6; int N,S,A,C,R; double M,e,t; vector<int> I(MAX); map<int,int> cnt; void solve(){ M=1e9; for (int s=0;s<=15;++s){ for (int a=0;a<=15;++a){ for (int c=0;c<=15;++c){ R=s; e=0; cnt.clear(); for (int i=0;i<N;++i){ R=(a*R+c)%MAX; ++cnt[(I[i]+R)%MAX]; } for (auto p:cnt){ t=(double)p.second; e-=t/(double)N*log(t/(double)N); } if (e+EPS<M){ M=e; S=s,A=a,C=c; } } } } cout << S << ' ' << A << ' ' << C << '\n'; } int main(){ cin.tie(0); ios::sync_with_stdio(false); while(cin >> N,N){ for (int i=0;i<N;++i) cin >> I[i]; solve(); } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#define _CRT_SECURE_NO_WARNINGS #pragma comment (linker, "/STACK:526000000") #include "bits/stdc++.h" using namespace std; typedef string::const_iterator State; #define eps 1e-11L #define MAX_MOD 1000000007LL #define GYAKU 500000004LL #define MOD 998244353LL #define seg_size 262144*2LL #define pb push_back #define mp make_pair typedef long long ll; #define REP(a,b) for(long long (a) = 0;(a) < (b);++(a)) #define ALL(x) (x).begin(),(x).end() unsigned long xor128() { static unsigned long x = 123456789, y = 362436069, z = 521288629, w = time(NULL); unsigned long t = (x ^ (x << 11)); x = y; y = z; z = w; return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))); } void init() { iostream::sync_with_stdio(false); cout << fixed << setprecision(20); } #define int ll long double calc(vector<int> a) { map<int, int> next; REP(i, a.size()) { next[a[i]]++; } long double ans = 0; for (auto x : next) { ans -= (long double)x.second / (long double)a.size() * log((long double)x.second / (long double)a.size()); } return ans; } long double gogo(tuple<int, int, int> a,vector<int> b) { vector<int> c; c.push_back(get<0>(a)); while (c.size()-1 != b.size()) { c.push_back((c.back() * get<1>(a)) + get<2>(a)); c.back() %= 256; } REP(i, b.size()) { b[i] += c[i+1]; b[i] %= 256; } return calc(b); } void solve() { while (true) { int n; cin >> n; if (n == 0) return; vector<int> inputs; REP(i, n) { int a; cin >> a; inputs.push_back(a); } tuple<int, int, int> ans = make_tuple(0, 0, 0); REP(S, 16) { REP(A, 16) { REP(C, 16) { if (gogo(ans, inputs)-eps > gogo(make_tuple(S, A, C),inputs)) { ans = make_tuple(S, A, C); } } } } cout << get<0>(ans) << " " << get<1>(ans) << " " << get<2>(ans) << endl; } } #undef int int main() { init(); solve(); }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <cassert> #include <iostream> #include <algorithm> #include <stack> #include <queue> #include <vector> #include <set> #include <map> #include <bitset> #include <functional> #include <numeric> using namespace std; #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repl(i,0,n) #define mp(a,b) make_pair((a),(b)) #define pb(a) push_back((a)) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<((x))<<endl #define fi first #define se second #define INF 2147483600 #define long long long int s,a,c; int R(int i){ return (a*i+c)%256; } double calch(vector<int> &vec){ vector<int> cnt(256, 0); for(int i:vec) cnt[i]++; double ret=0; rep(i,256) if(cnt[i]>0) ret += (double)cnt[i] * log((double)cnt[i]); return ret; } int main(){ int n; while(cin>>n, n){ vector<int> vec(n); rep(i,n) cin>>vec[i]; double best=-INF; int bs=-1,ba=-1,bc=-1; for(s=0; s<16; s++) for(a=0; a<16; a++) for(c=0; c<16; c++){ vector<int> o(vec); int pre=s; rep(i,n){ pre = R(pre); o[i] = (o[i]+pre)%256; } double h = calch(o); if(best < h){ best = h; bs=s; ba=a; bc=c; } } cout<<bs<<" "<<ba<<" "<<bc<<endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for (int i=(a);i<(b);i++) #define RFOR(i,a,b) for (int i=(b)-1;i>=(a);i--) #define REP(i,n) for (int i=0;i<(n);i++) #define RREP(i,n) for (int i=(n)-1;i>=0;i--) #define ALL(a) (a).begin(),(a).end() #define DEBUG(a) "(" << #a << ": " << (a) << ")" template<typename T> void chmin(T &x, T y) { x = min(x, y); } template<typename T> void chmax(T &x, T y) { x = max(x, y); } typedef long long int lli; typedef long double ld; typedef tuple<int,int> P; const int INF = INT_MAX/2 - 1; const ld EPS = 1e-14; const int dx[4] = {0, 1, 0, -1}; // {-1, 0, 1, -1, 1, -1, 0, 1}; const int dy[4] = {1, 0, -1, 0}; // {-1, -1, -1, 0, 0, 1, 1, 1}; const int M = 256; ld entropy(const vector<int> &v) { ld H = 0; for (int x : v) { if (x) { H -= x * log((ld)x); } } return H; } ld calc(int S, int A, int C, const vector<int> &I) { vector<int> table(M); for (int i = 0, len = I.size(), R = S; i < len; ++i) { R = (A * R + C) % M; table[(I[i] + R) % M]++; } return entropy(table); } int main() { cout << fixed << setprecision(10); int N; while (cin >> N and N) { vector<int> I(N); REP(i, N) cin >> I[i]; ld ans = INF; int S = -1, A = -1, C = -1; REP(s, 16) REP(a, 16) REP(c, 16) { ld H = calc(s, a, c, I); if (ans > H + EPS) { ans = H; S = s, A = a, C = c; } } cout << S << " " << A << " " << C << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<iostream> #include<cmath> using namespace std; int n, I[1 << 10], R[1 << 10], O[1 << 10], V[1 << 10]; int main() { while (true) { cin >> n; if (n == 0)break; for (int i = 1; i <= n; i++) { cin >> I[i]; } long double minx = 100.0; int T = 0; for (int S = 0; S < 16; S++) { for (int A = 0; A < 16; A++) { for (int C = 0; C < 16; C++) { R[0] = S; long double sum = 0.0; for (int i = 1; i <= n; i++) R[i] = (A*R[i - 1] + C) % 256; for (int i = 1; i <= n; i++) O[i] = (I[i] + R[i]) % 256; for (int i = 0; i < 256; i++) V[i] = 0; for (int i = 1; i <= n; i++) V[O[i]]++; for (int i = 0; i < 256;i++){ if (V[i] >= 1) { long double F = 1.0*V[i] / n; sum -= F*log(F); } } if (sum < minx) { minx = sum; T = S * 256 + A * 16 + C; } } } } cout << T / 256 << ' ' << (T / 16) % 16 << ' ' << T % 16 << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
import java.util.*; public class Main { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); while(true) { int N = stdIn.nextInt(); if(N == 0) break; int[] I = new int[N+1]; for(int i = 1; i <= N; i++) { I[i] = stdIn.nextInt(); } int M = 256; int S = 99999999; int A = 99999999; int C = 99999999; double min = 99999999; for(int s = 0; s <= 15; s++) { for(int a = 0; a <= 15; a++) { for(int c = 0; c <= 15; c++) { int R[] = new int[N+1]; R[0] = s; for(int i = 1; i <= N; i++) { R[i] = (a * R[i-1] + c)%M; } int O[] = new int[256]; for(int i = 1; i <= N; i++) { O[(I[i] + R[i]) % M]++; } double H = 0; for(int i = 0; i < 256; i++) { if(O[i] > 0) { H -= O[i] / (double)N * Math.log(O[i] / (double)N); } } if(H + 1e-10 < min) { min = H; S = s; A = a; C = c; } } } } System.out.println(S + " " + A + " " + C); } } }
JAVA
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <bits/stdc++.h> typedef long long LL; #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) using namespace std; int main(void) { for(;;){ int n; cin >> n; if(!n) return 0; vector<int> l; double H=1e+5; l.resize(n); REP(i,n) cin >> l[i]; int anss,ansa,ansc; REP(s,16) REP(a,16) REP(c,16){ vector<int> r; r.resize(n); r[0]=(a*s+c)%256; REP(i,n-1) r[i+1]=(a*r[i]+c)%256; vector<int> his; his.assign(256,0); REP(i,n) ++his[(l[i]+r[i])%256]; double tmpH=0.0; REP(i,256) if(his[i]) tmpH-=1.0*his[i]/n*log(1.0*his[i]/n); if(tmpH+1e-6<H){ anss=s; ansa=a; ansc=c; H=tmpH; } } cout << anss << ' ' << ansa << ' ' << ansc << endl; } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)(n); ++i) #define REP(i,n) FOR(i,0,n) #define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cerr<<*i<<" "; cerr<<endl; } inline bool valid(int x, int y, int W, int H){ return (x >= 0 && y >= 0 && x < W && y < H); } typedef long long ll; const int INF = 100000000; const double EPS = 1e-8; const int MOD = 1000000007; int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1}; int main(){ int N; while(cin>>N && N){ vector<int> l(N); REP(i, N) cin>>l[i]; int M = 256; int as, aa, ac; double ent = 1e32; REP(S, 16)REP(A, 16)REP(C, 16){ vector<int> R(N + 1); R[0] = S; REP(i, N){ R[i + 1] = (A * R[i] + C); while(R[i + 1] >= M) R[i + 1] -= M; } REP(i, N){ R[i + 1] += l[i]; while(R[i + 1] >= M) R[i + 1] -= M; } double cnt[256] = {}; REP(i, N) cnt[R[i + 1]] += 1.0; double e = 0; REP(i, 256)if(cnt[i] != 0){ double c = cnt[i]; e += -c/N * log(c/N); if(!(e + EPS < ent)) goto END; } ent = e; as = S, aa = A, ac = C; END:; } printf("%d %d %d\n", as, aa, ac); } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<iostream> #include<string.h> #include<math.h> #define M 256 using namespace std; int main() { int N; while (cin >> N && N != 0) { int L[M]; for (int i = 0; i < N; i++) { cin >> L[i]; } int ansS = 0, ansA = 0, ansC = 0; double minH = 1e10; for (int s = 0; s <= 15; s++) { for (int a = 0; a <= 15; a++) { for (int c = 0; c <= 15; c++) { int R[M]; int count[M]; memset(count, 0, sizeof (int) * M); R[0] = (a * s + c) % M; for (int i = 1; i < N; i++) { R[i] = (a * R[i - 1] + c) % M; } double h = 0.0; for (int i = 0; i < N; i++) { count[(L[i] + R[i]) % M]++; } for (int i = 0; i < M; i++) { if (count[i] <= 0)continue; h -= ((double)count[i] / N) * log((double) count[i] / N); } if (h + (1e-10) < minH) { ansS = s; ansA = a; ansC = c; minH = h; } } } } cout << ansS << " " << ansA << " " << ansC << endl; } return 0; }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include<stdio.h> #include<algorithm> #include<math.h> using namespace std; int b[256]; int c[256]; int d[256]; int main(){ int a; while(scanf("%d",&a),a){ for(int i=0;i<a;i++){ scanf("%d",b+i); } int S=0,A=0,C=0; double min=999999999; for(int i=0;i<16;i++){ for(int j=0;j<16;j++){ for(int k=0;k<16;k++){ c[0]=i*j+k; for(int l=1;l<a;l++){ c[l]=(c[l-1]*j+k)&255; } for(int l=0;l<256;l++)d[l]=0; for(int l=0;l<a;l++)d[(b[l]+c[l])&255]++; double val=0; for(int l=0;l<256;l++)if(d[l])val-=(double)d[l]/a*log((double)d[l]/a); if(min>val+0.00000001){ min=val; S=i;A=j;C=k; } } } } printf("%d %d %d\n",S,A,C); } }
CPP
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - 1). Then, using the pseudo-random number series R(⋅), we obtain another string O(⋅) as the output by the following formula: <image> Your task is to write a program that shows the parameters S, A, and C such that the information entropy of the output string O(⋅) is minimized. Here, the information entropy H is given by the following formula: <image> where N is the length of the string and #(x) is the number of occurences of the alphabet x. Input The input consists of multiple datasets. Each dataset has the following format: N I(1) I(2) ... I(N) N does not exceed 256. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print in a line the values of the three parameters S, A, and C separated by a single space. If more than one solution gives the same minimum entropy, choose the solution with the smallest S, A, and then C. Example Input 5 5 4 3 2 1 5 7 7 7 7 7 10 186 8 42 24 154 40 10 56 122 72 0 Output 0 1 1 0 0 0 8 7 14
7
0
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)(n); ++i) #define REP(i,n) FOR(i,0,n) #define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cerr<<*i<<" "; cerr<<endl; } inline bool valid(int x, int y, int W, int H){ return (x >= 0 && y >= 0 && x < W && y < H); } typedef long long ll; const int INF = 100000000; const double EPS = 1e-8; const int MOD = 1000000007; int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1}; int main(){ int N; while(cin>>N && N){ vector<int> l(N); REP(i, N) cin>>l[i]; int M = 256; int as, aa, ac; double ent = 1e32; REP(S, 16)REP(A, 16)REP(C, 16){ vector<int> R(N + 1); R[0] = S; REP(i, N) R[i + 1] = (A * R[i] + C) % M; REP(i, N) R[i + 1] = (R[i + 1] + l[i]) % M; double cnt[256] = {}; REP(i, N) cnt[R[i + 1]] += 1.0; double e = 0; REP(i, 256)if(cnt[i] != 0){ double c = cnt[i]; e += -c/N * log(c/N); } if(e + EPS < ent){ ent = e; as = S, aa = A, ac = C; } } printf("%d %d %d\n", as, aa, ac); } return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<complex> #include<bitset> #include<stack> #include<unordered_map> #include<utility> using namespace std; typedef long long ll; typedef unsigned long long ul; typedef unsigned int ui; typedef long double ld; typedef pair<int, int> P; typedef pair<ll, ll> LP; typedef pair<ld, ld> LDP; typedef complex<ld> Point; const ll mod = 1000000007; const ld INF = 1e+30; const ld eps = 1e-8; const ld pi = acos(-1.0); #define stop char nyaa;cin>>nyaa; #define rep(i,n) for(int i=0;i<n;i++) #define per(i,n) for(int i=n-1;i>=0;i--) #define Rep(i,sta,n) for(int i=sta;i<n;i++) #define rep1(i,n) for(int i=1;i<=n;i++) #define per1(i,n) for(int i=n;i>=1;i--) #define Rep1(i,sta,n) for(int i=sta;i<=n;i++) int w, h; int dx[4] = { 1,0,-1,0 }; int dy[4] = { 0,1,0,-1 }; int sx, sy; queue<P> q; char mp[500][500]; bool used[500][500]; ld d[500][500]; vector<ld> a, b; ld sa, sb; bool comp(LDP x, LDP y) { return x.first - x.second < y.first - y.second; } void solve() { cin >> w >> h; rep(i, h) { rep(j, w) { d[i][j] = (ld)h*w*1000000; } } rep(i, h) { rep(j, w) { cin >> mp[i][j]; if (mp[i][j] == 's') { sx = i, sy = j; mp[i][j] = '.'; } else if (mp[i][j] == 'g') { q.push({ i,j }); used[i][j] = true; } } } int tmp = 0; while (!q.empty()) { int len = q.size(); rep(aa, len) { P p = q.front(); q.pop(); int x = p.first, y = p.second; d[x][y] = tmp; rep(j, 4) { int nx = x + dx[j], ny = y + dy[j]; if (mp[nx][ny] == '.' && !used[nx][ny]) { used[nx][ny] = true; q.push({ nx,ny }); } } } tmp++; } rep(i, h) { rep(j, w) { if (mp[i][j] == '.')a.push_back(d[i][j]); if (sx == i && sy == j)sa = d[i][j]; } } rep(i, h)rep(j, w) { used[i][j] = false; d[i][j] = (ld)h*w*1000000; if (mp[i][j] == '*') { used[i][j] = true; q.push({ i,j }); } } tmp = 0; while (!q.empty()) { int len = q.size(); rep(aa, len) { P p = q.front(); q.pop(); int x = p.first, y = p.second; d[x][y] = tmp; rep(j, 4) { int nx = x + dx[j], ny = y + dy[j]; if (mp[nx][ny] == '.' && !used[nx][ny]) { used[nx][ny] = true; q.push({ nx,ny }); } } } tmp++; } rep(i, h)rep(j, w) { if (mp[i][j] == '.') { //cout << i << " " << j << " " << d[i][j] << endl; b.push_back(d[i][j]); } if (sx == i && sy == j) { sb = d[i][j]; } } cout << fixed << setprecision(10); int sz = a.size(); ld ans = INF; vector<LDP> v; rep(i, sz) { v.push_back({ a[i],b[i] }); } sort(v.begin(), v.end(), comp); ld sum = 0; rep(i, sz) { sum += b[i]; } rep(i, sz) { //cout << v[i].first << " " << v[i].second << endl; //cout << v[i].first - v[i].second << endl; sum -= v[i].second; sum += v[i].first; ld csum = sum * sz / (ld)(1 + i); ld le = v[i].first - v[i].second; ld ri = INF; if (i + 1 < sz - 1) { ri = v[i + 1].first - v[i + 1].second; } //cout << sum << endl; if (le < csum / (ld)sz&&csum/(ld)sz<ri) { ans = min(ans, csum); } } cout << min(sa, sb + ans / (ld)sz) << endl; } int main() { cin.tie(0); ios::sync_with_stdio(false); solve(); //stop return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-10) #define equals(a,b) (fabs((a)-(b))<EPS) using namespace std; typedef long double ld; const int MAX = 501,IINF = INT_MAX; const ld LDINF = 1e100; int H,W,sx,sy,gx,gy; ld mincost[MAX][MAX][2]; // mincost[][][0] => from start, [1] = > from star char c[MAX][MAX]; bool ban[MAX][MAX]; vector<int> star,plane; int dx[] = {0,1,0,-1}; int dy[] = {1,0,-1,0}; inline bool isValid(int x,int y) { return 0 <= x && x < W && 0 <= y && y < H; } inline void bfs(vector<int> sp,vector<int> Forbidden,int type){ rep(i,H)rep(j,W) mincost[i][j][type] = LDINF, ban[i][j] = false; queue<int> que; rep(i,(int)sp.size()) que.push(sp[i]), mincost[sp[i]/W][sp[i]%W][type] = 0; rep(i,(int)Forbidden.size()) ban[Forbidden[i]/W][Forbidden[i]%W] = true; while(!que.empty()){ int cur = que.front(); que.pop(); rep(i,4){ int nx = cur % W + dx[i], ny = cur / W + dy[i]; if( c[ny][nx] == '#' ) continue; if( ban[ny][nx] ) continue; if( mincost[ny][nx][type] == LDINF ) { mincost[ny][nx][type] = mincost[cur/W][cur%W][type] + 1; que.push(nx+ny*W); } } } } bool check(ld E){ ld T = 0; rep(i,(int)plane.size()){ int x = plane[i] % W, y = plane[i] / W; T += min(mincost[y][x][0],mincost[y][x][1]+E); } ld len = plane.size(); return len * E > T; } int main(){ cin >> W >> H; rep(i,H)rep(j,W){ cin >> c[i][j]; if( c[i][j] == 's' ) sx = j, sy = i, c[i][j] = '.'; if( c[i][j] == 'g' ) gx = j, gy = i; if( c[i][j] == '*' ) star.push_back(j+i*W); if( c[i][j] == '.' ) plane.push_back(j+i*W); } vector<int> sp,forbidden; sp.push_back(gx+gy*W); forbidden = star; forbidden.push_back(gx+gy*W); bfs(sp,forbidden,0); sp = star; forbidden.push_back(gx+gy*W); //forbidden.clear(); bfs(sp,forbidden,1); ld L = 0, R = 1e10, M = 0; rep(i,60){ M = ( L + R ) * (ld)0.5; if( check(M) ) R = M; else L = M; } cout << setiosflags(ios::fixed) << setprecision(20) << min((ld)mincost[sy][sx][0],(ld)mincost[sy][sx][1]+L) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <cstdio> #include <utility> #include <queue> #include <iostream> using namespace std; int main(){ int W, H, gx, gy, sx, sy, n = 0; cin >> W >> H; string M[H]; vector< pair<int,int> > springs; for(int i = 0; i < H; ++i){ cin >> M[i]; for(int j = 0; j < W; ++j){ if(M[i][j] == 'g'){ gx = i; gy = j; M[i][j] = '.'; }else if(M[i][j] == 's'){ sx = i; sy = j; M[i][j] = '.'; ++n; }else if(M[i][j] == '.') ++n; else if(M[i][j] == '*'){ springs.push_back(make_pair(i,j)); } } } double INF = (1e10), l = 0.0, r = INF, exp_[H][W], exp[H][W]; int d[] = {1,0,-1,0}; queue< pair<int,int> > que; que.push(make_pair(gx,gy)); for(int i = 0; i < H; ++i){ for(int j = 0; j < W; ++j){ exp_[i][j] = INF; exp[i][j] = INF; } } exp_[gx][gy] = 0.0; while(!que.empty()){ int x = que.front().first, y = que.front().second; que.pop(); for(int k = 0; k < 4; ++k){ int x_ = x + d[k], y_ = y + d[(k+1)%4]; if(x_ >= H || x_ < 0 || y_ >= W || y_ < 0) continue; char c = M[x_][y_]; if(c == '.' && exp_[x_][y_] > exp_[x][y]+1){ exp_[x_][y_] = exp_[x][y]+1; que.push(make_pair(x_,y_)); } } } vector< vector<double> > dist_from_spring(H, vector<double>(W, INF)); for(int i = 0; i < springs.size(); ++i){ queue< pair<int,int> > que2; que2.push(make_pair(springs[i].first, springs[i].second)); dist_from_spring[springs[i].first][springs[i].second] = 0; while(!que2.empty()){ int x = que2.front().first, y = que2.front().second; que2.pop(); for(int k = 0; k < 4; ++k){ int x_ = x + d[k], y_ = y + d[(k+1)%4]; if(x_ >= H || x_ < 0 || y_ >= W || y_ < 0) continue; char c = M[x_][y_]; if(c == '.' && (dist_from_spring[x_][y_] > dist_from_spring[x][y]+1)){ que2.push(make_pair(x_,y_)); dist_from_spring[x_][y_] = dist_from_spring[x][y]+1; } } } } for(int t = 0; t < 100; ++t){ double mean = (l+r)/2.0; long double s = 0.0; for(int i = 0; i < H; ++i){ for(int j = 0; j < W; ++j){ if(M[i][j] == '.'){ exp[i][j] = min(exp_[i][j], dist_from_spring[i][j]+mean); s += exp[i][j]; } } } if(s/n < mean){ r = mean; }else{ l = mean; } } printf("%.12f\n",exp[sx][sy]); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <vector> #include <iostream> #include <queue> #include <cassert> #include <tuple> using namespace std; typedef long long ll; typedef pair<int, int> P; typedef tuple<int, int, int> PD; typedef long double ld; const int MN = 550; const int INT_INF = 1<<28; const int d4[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; int w, h; string g[MN]; int dist2g[MN][MN]; int dist2b[MN][MN]; bool bc(int x, int y) { return (0 <= x && x < w && 0 <= y && y < h); } void init2g() { queue<PD> q; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { dist2g[y][x] = INT_INF; if (g[y][x] == 'g') { q.push(PD(x, y, 0)); } } } while (!q.empty()) { int x, y, d; tie(x, y, d) = q.front(); q.pop(); // assert(g[y][x] != '#'); if (dist2g[y][x] < INT_INF) continue; dist2g[y][x] = d; for (int i = 0; i < 4; i++) { int nx = x + d4[i][0], ny = y + d4[i][1]; if (!bc(nx, ny)) continue; if (g[ny][nx] == '#' || g[ny][nx] == '*') continue; q.push(PD(nx, ny, d+1)); } } } void init2b() { queue<PD> q; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { dist2b[y][x] = INT_INF; if (g[y][x] == '*') { q.push(PD(x, y, 0)); } } } while (!q.empty()) { int x, y, d; tie(x, y, d) = q.front(); q.pop(); if (dist2b[y][x] < INT_INF) continue; // assert(g[y][x] != '#'); dist2b[y][x] = d; for (int i = 0; i < 4; i++) { int nx = x + d4[i][0], ny = y + d4[i][1]; if (!bc(nx, ny)) continue; if (g[ny][nx] == '#') continue; q.push(PD(nx, ny, d+1)); } } } int main() { cin >> w >> h; for (int i = 0; i < h; i++) { cin >> g[i]; } int pc = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (g[y][x] == '#') continue; if (g[y][x] == '*') continue; if (g[y][x] == 'g') continue; pc++; } } init2g(); init2b(); /* printf("pc %d\n", pc); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (dist2g[y][x] == INT_INF) { printf("-1 "); } else { printf("%2d ", dist2g[y][x]); } } printf("\n"); } printf("end\n"); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (dist2b[y][x] == INT_INF) { printf("-1 "); } else { printf("%2d ", dist2b[y][x]); } } printf("\n"); } printf("end\n");*/ int sx, sy; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (g[y][x] == 's') { sx = x; sy = y; } } } if (dist2b[sy][sx] == INT_INF) { assert(dist2g[sy][sx] < INT_INF); printf("%d\n", dist2g[sy][sx]); return 0; } ld l = 0, r = 1e20; for (int i = 0; i < 200; i++) { //printf("%Lf %Lf\n", l, r); ld md = (l+r)/2; ld e = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (g[y][x] == '#') continue; if (g[y][x] == '*') continue; if (g[y][x] == 'g') continue; if (dist2g[y][x] == INT_INF) { e += dist2b[y][x] + md; continue; } e += min<ld>(dist2g[y][x], dist2b[y][x]+md); } } e /= pc; //printf("emd %Lf %Lf\n", e, md); if (e > md) { l = md; } else { r = md; } } if (dist2g[sy][sx] == INT_INF) { printf("%.20Lf\n", dist2b[sy][sx]+l); return 0; } printf("%.20Lf\n", min<ld>(dist2g[sy][sx], dist2b[sy][sx]+l)); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<iostream> #include<algorithm> #include<vector> #include<queue> #include<map> #include<set> #include<string> #include<stack> #include<cstdio> #include<cmath> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int,int> P; typedef pair<int,P> P1; #define fr first #define sc second #define mp make_pair #define pb push_back #define rep(i,x) for(int i=0;i<x;i++) #define rep1(i,x) for(int i=1;i<=x;i++) #define rrep(i,x) for(int i=x-1;i>=0;i--) #define rrep1(i,x) for(int i=x;i>0;i--) #define sor(v) sort(v.begin(),v.end()) #define rev(s) reverse(s.begin(),s.end()) #define lb(vec,a) lower_bound(vec.begin(),vec.end(),a) #define ub(vec,a) upper_bound(vec.begin(),vec.end(),a) #define uniq(vec) vec.erase(unique(vec.begin(),vec.end()),vec.end()) #define mp1(a,b,c) P1(a,P(b,c)) const ld MAX = 10000000000000; const ld EPS = 0.0000000001; const int dir_4[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; const int dir_8[8][2]={{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}}; int main(){ static int w,h; static char c[502][502]; scanf("%d%d",&w,&h); rep(i,h){ scanf("\n"); rep(j,w){ scanf("%c",&c[i][j]); } } static ld a[502][502]; static bool used[502][502]; static queue<pair<ld,P>> que; rep(i,h)rep(j,w){ if(c[i][j] == 'g'){ a[i][j] = 0; que.push(pair<ld,P>(0,P(i,j))); } else a[i][j] = MAX; used[i][j] = false; } while(!que.empty()){ pair<ld,P> p = que.front(); que.pop(); if(!used[p.sc.fr][p.sc.sc]){ rep(i,4){ int nx = p.sc.fr + dir_4[i][0]; int ny = p.sc.sc + dir_4[i][1]; if(c[nx][ny] == '#' || c[nx][ny] == '*')continue; if(a[nx][ny] > a[p.sc.fr][p.sc.sc] + 1.0){ a[nx][ny] = a[p.sc.fr][p.sc.sc] + 1.0; que.push(pair<ld,P>(a[nx][ny],P(nx,ny))); } } used[p.sc.fr][p.sc.sc] = true; } } static ld b[502][502]; rep(i,h)rep(j,w){ if(c[i][j] == '*'){ b[i][j] = 0; que.push(pair<ld,P>(0,P(i,j))); } else b[i][j] = MAX; used[i][j] = false; } while(!que.empty()){ pair<ld,P> p = que.front(); que.pop(); if(!used[p.sc.fr][p.sc.sc]){ rep(i,4){ int nx = p.sc.fr + dir_4[i][0]; int ny = p.sc.sc + dir_4[i][1]; if(c[nx][ny] == '#' || c[nx][ny] == '*')continue; if(b[nx][ny] > b[p.sc.fr][p.sc.sc] + 1.0){ b[nx][ny] = b[p.sc.fr][p.sc.sc] + 1.0; que.push(pair<ld,P>(b[nx][ny],P(nx,ny))); } } used[p.sc.fr][p.sc.sc] = true; } } bool t = false; rep(i,h)rep(j,w){ if(c[i][j] == 's' && b[i][j] == MAX)t = true; } rep(i,h)rep(j,w){ if(a[i][j] == MAX && b[i][j] == MAX)c[i][j] = '#'; if(t && a[i][j] == MAX)c[i][j] = '#'; } cout.precision(20); ld l = 0.0 , r = MAX; rep(ppp,200){ ld m = (l+r)/2; ld sum = 0.0 , cnt = 0.0; rep(i,h)rep(j,w){ if(c[i][j] == '#' || c[i][j] == '*' || c[i][j] == 'g')continue; sum += min ( a[i][j] , m+b[i][j] ); cnt += 1.0; } //cout << l << " " << r << ":" << endl; //cout << "m = " << m << endl; //cout << "sum = " << sum << ",cnt = " << cnt << endl; if(m*cnt > sum)r = m; else l = m; } /*rep(i,h){ rep(j,w){ if(a[i][j] >= MAX-1.0){ printf("-"); } else { printf("%d",(int)a[i][j]); } } puts(""); } rep(i,h){ rep(j,w){ if(b[i][j] >= MAX-1.0){ printf("-"); } else { printf("%d",(int)b[i][j]); } } puts(""); }*/ cout.precision(20); rep(i,h)rep(j,w){ if(c[i][j] == 's'){ cout << min ( a[i][j] , l+b[i][j] ) << endl; } } }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; #ifdef _WIN32 #define scanfll(x) scanf("%I64d", x) #define printfll(x) printf("%I64d", x) #else #define scanfll(x) scanf("%lld", x) #define printfll(x) printf("%lld", x) #endif #define rep(i,n) for(long long i = 0; i < (long long)(n); i++) #define repi(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++) #define pb push_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define mt make_tuple #define mp make_pair template<class T1, class T2> bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); } template<class T1, class T2> bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); } using ll = long long; using ld = long double; using vll = vector<ll>; using vvll = vector<vll>; using vld = vector<ld>; using vi = vector<int>; using vvi = vector<vi>; vll conv(vi& v) { vll r(v.size()); rep(i, v.size()) r[i] = v[i]; return r; } using P = pair<ll, ll>; template <typename T, typename U> ostream &operator<<(ostream &o, const pair<T, U> &v) { o << "(" << v.first << ", " << v.second << ")"; return o; } template<size_t...> struct seq{}; template<size_t N, size_t... Is> struct gen_seq : gen_seq<N-1, N-1, Is...>{}; template<size_t... Is> struct gen_seq<0, Is...> : seq<Is...>{}; template<class Ch, class Tr, class Tuple, size_t... Is> void print_tuple(basic_ostream<Ch,Tr>& os, Tuple const& t, seq<Is...>){ using s = int[]; (void)s{0, (void(os << (Is == 0? "" : ", ") << get<Is>(t)), 0)...}; } template<class Ch, class Tr, class... Args> auto operator<<(basic_ostream<Ch, Tr>& os, tuple<Args...> const& t) -> basic_ostream<Ch, Tr>& { os << "("; print_tuple(os, t, gen_seq<sizeof...(Args)>()); return os << ")"; } ostream &operator<<(ostream &o, const vvll &v) { rep(i, v.size()) { rep(j, v[i].size()) o << v[i][j] << " "; cout << endl; } return o; } template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]"; return o; } template <typename T> ostream &operator<<(ostream &o, const set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; } template <typename T, typename U> ostream &operator<<(ostream &o, const map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; } template <typename T, typename U> ostream &operator<<(ostream &o, const unordered_map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it; o << "]"; return o; } void printbits(ll mask, ll n) { rep(i, n) { cout << !!(mask & (1ll << i)); } cout << endl; } #define ldout fixed << setprecision(40) static const double EPS = 1e-14; static const long long INF = 1e18; static const long long mo = 1e9+7; // ???????°???°???????????¢?´¢ ld BinarySearchReal(ld rl, ld rr, function<bool(ld)> f) { rep(i, 200) { ld m = (rl + rr) / 2; f(m)?rr=m:rl=m; } return rl; } void BinarySearchRealInteractive(ld rl, ld rr, function<bool(ld)> f) { while (1) { cout << "####" << endl; ld tmp; cin >> tmp; if (rl > tmp) {cout << "Out of range: too small" << endl; continue; } if (rr < tmp) {cout << "Out of range: too large" << endl; continue; } ld ret = f(tmp); cout << tmp << " : " << ret << endl; } } char m[500][500] = {}; ll b[500][500] = {}; ll g[500][500] = {}; void print_map(ll w, ll h) { rep(hi, h) { rep(wi, w) { cout << m[hi][wi]; } cout << endl; } } void print_bane(ll w, ll h) { rep(hi, h) { rep(wi, w) { if (b[hi][wi] == INF) cout << -1 << "\t"; else cout << b[hi][wi] << "\t"; } cout << endl; } } void print_goal(ll w, ll h) { rep(hi, h) { rep(wi, w) { if (g[hi][wi] == INF) cout << -1 << "\t"; else cout << g[hi][wi] << "\t"; } cout << endl; } } int main(void) { cin.tie(0); ios::sync_with_stdio(false); ll w, h; cin >> w >> h; rep(hi, h) { rep(wi, w) { cin >> m[hi][wi]; } } // print_map(w, h); rep(hi, h) { rep(wi, w) { b[hi][wi] = INF; } } rep(hi, h) { rep(wi, w) { g[hi][wi] = INF; } } vector<ll> dh = {1, 0, -1, 0}; vector<ll> dw = {0, 1, 0, -1}; queue<P> q; rep(hi, h) { rep(wi, w) { if (m[hi][wi] == '*') { q.push(P(hi, wi)); b[hi][wi] = 0; } } } while (!q.empty()) { P pos = q.front(); q.pop(); ll hi = pos.fi, wi = pos.se; ll pos_dist = b[hi][wi]; rep(d, 4) { ll next_hi = hi + dh[d]; ll next_wi = wi + dw[d]; if (next_hi < h && next_hi >= 0 && next_wi < w && next_wi >= 0 && (m[next_hi][next_wi] == '.' || m[next_hi][next_wi] == 's') && b[next_hi][next_wi] == INF) { b[next_hi][next_wi] = pos_dist + 1; q.push(P(next_hi, next_wi)); } } } // cout << endl; // print_bane(w, h); rep(hi, h) { rep(wi, w) { if (m[hi][wi] == 'g') { q.push(P(hi, wi)); g[hi][wi] = 0; } } } while (!q.empty()) { P pos = q.front(); q.pop(); ll hi = pos.fi, wi = pos.se; ll pos_dist = g[hi][wi]; rep(d, 4) { ll next_hi = hi + dh[d]; ll next_wi = wi + dw[d]; if (next_hi < h && next_hi >= 0 && next_wi < w && next_wi >= 0 && (m[next_hi][next_wi] == '.' || m[next_hi][next_wi] == 's') && g[next_hi][next_wi] == INF) { g[next_hi][next_wi] = pos_dist + 1; q.push(P(next_hi, next_wi)); } } } // cout << endl; // print_goal(w, h); vector<P> bg; rep(hi, h) { rep(wi, w) { if (m[hi][wi] == '.' || m[hi][wi] == 's') { bg.pb(P(b[hi][wi], g[hi][wi])); } } } ll n = bg.size(); // !!!!!!!!!!!!!!!!!!!! 1e8 !!!!!!!!!!!!!!!!!!!! function<bool(ld)> f = [&](ld e){ ll k = 0; ll bsum = 0; ll gsum = 0; for (auto x : bg) { if (x.fi + e < x.se) { k++; bsum += x.fi; } else { gsum += x.se; } } return e * (n - k) > bsum + gsum; }; ld e = BinarySearchReal(0, 1e40, f); // cout << e << endl; ll hs = -1, ws = -1; rep(hi, h) { rep(wi, w) { if (m[hi][wi] == 's') { hs = hi; ws = wi; } } } cout << ldout << min((ld)b[hs][ws] + e, (ld)g[hs][ws]) << endl; // 5 1 // .g...s* // // // 7 1 // .g...s* // // 8 1 // .g...s.* // # e = 2 // # e = (1+1+2+3)/5 + (1+e)/5 // // e??£?????????????????§?????????????????¨???????????? // sample 2??§e=2.8e15??????????????? return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
// #define _GLIBCXX_DEBUG // for STL debug (optional) #include <iostream> #include <iomanip> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex> #include <cmath> #include <limits> #include <cfloat> #include <climits> #include <ctime> #include <cassert> #include <numeric> #include <fstream> #include <functional> #include <bitset> using namespace std; #define debug(...) fprintf(stderr, __VA_ARGS__) #define int long long int template<typename T> void chmax(T &a, T b) {a = max(a, b);} template<typename T> void chmin(T &a, T b) {a = min(a, b);} template<typename T> void chadd(T &a, T b) {a = a + b;} typedef pair<int, int> pii; typedef long long ll; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; const ll INF = 1001001001001001LL; const ll MOD = 1000000007LL; int W, H; char board[510][510]; long double dp[510][510]; void calc(long double bin_v) { fill(dp[0], dp[H+1], INF); queue< tuple<int, int, long double> > que; for(int i=0; i<H; i++) { for(int j=0; j<W; j++) { if(board[i][j] == 'g') { dp[i][j] = 0.0; que.emplace(i, j, dp[i][j]); } if(board[i][j] == '*') { dp[i][j] = bin_v; que.emplace(i, j, dp[i][j]); } } } while(que.size()) { int x, y; long double val; tie(x, y, val) = que.front(); que.pop(); for(int k=0; k<4; k++) { int nx = x + dx[k], ny = y + dy[k]; if(board[nx][ny] == '#') continue; if(board[nx][ny] == '*') continue; if(dp[nx][ny] > val + 1) { dp[nx][ny] = val + 1; que.emplace(nx, ny, val + 1); } } } } signed main() { cin >> W >> H; int sx, sy, gx, gy, cnt = 0; for(int i=0; i<H; i++) { for(int j=0; j<W; j++) { cin >> board[i][j]; if(board[i][j] == 's') sx = i, sy = j; if(board[i][j] == 'g') gx = i, gy = j; if(board[i][j] == 's' or board[i][j] == '.') { cnt++; } } } // fprintf(stderr, "cnt = %lld\n", cnt); long double ub = INF, lb = 0; for(int r=0; r<200; r++) { long double x = (ub + lb) / 2.0; calc(x); long double E = 0.0; for(int i=0; i<H; i++) { for(int j=0; j<W; j++) { if(board[i][j] == '.' or board[i][j] == 's') { E += dp[i][j]; } } } E /= cnt; if(E < x) ub = x; else lb = x; } long double x = ub; calc(x); // fprintf(stderr, "x = %.12f\n", x); printf("%.12Lf\n", dp[sx][sy]); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <vector> #include <string> #include <utility> #include <algorithm> #include <queue> #include <iomanip> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define rep(i,n) for(ll i = 0; i < (n); i++) #define fi first #define se second const ll INF = 1e15; int W, H; vector<string> brd; vector<vector<ll> > dist_spring; vector<vector<ll> > dist_goal; bool check(int y, int x) { return 0 <= y && y < H && 0 <= x && x < W; } void bfs(queue<pii> q, vector<vector<ll> > & res) { ll d = 0; queue<pii> nex; while(q.size()) { while(q.size()) { pii crd; crd = q.front(); q.pop(); res[crd.fi][crd.se] = min(res[crd.fi][crd.se], d); rep(i,4) { const int dxy[] = {0,1,0,-1,0}; int ny, nx; ny = crd.fi + dxy[i]; nx = crd.se + dxy[i+1]; if(check(ny,nx) && (brd[ny][nx] == '.' || brd[ny][nx] == 's') && res[ny][nx] == INF) { nex.push(pii(ny,nx)); res[ny][nx] = d+1; } } } q = nex; while(nex.size()) nex.pop(); d++; } } void make_dist_spring() { queue<pii> q; rep(i,H) { dist_spring.push_back(vector<ll>(W, INF)); rep(j,W) { if(brd[i][j] == '*') q.push(pii(i,j)); } } bfs(q, dist_spring); } void make_dist_goal() { queue<pii> q; rep(i,H) { dist_goal.push_back(vector<ll>(W,INF)); rep(j,W) { if(brd[i][j] == 'g') q.push(pii(i,j)); } } bfs(q, dist_goal); } int main() { pii st; cin >> W >> H; rep(i,H) { string s; cin >> s; brd.push_back(s); rep(j, W) { if(s[j] == 's') st = pii(i,j); } } make_dist_spring(); make_dist_goal(); double l, r, m; l = 0; r = INF; rep(i,100) { m = (l+r) / 2; double a, b; ll c, d, e; a = b = 0; c = d = e = 0; rep(j, H) { rep(k, W) { if(brd[j][k] == '.' || brd[j][k] == 's') { a += min((double)dist_goal[j][k], dist_spring[j][k] + m); if(dist_goal[j][k] > dist_spring[j][k] + m) { d += dist_spring[j][k]; e++; } else { d += dist_goal[j][k]; } c++; } } } a = d + e * m; b = c * m; if(a > b) l = m; else r = m; } cout << setprecision(15) << fixed << min((double)dist_goal[st.fi][st.se], dist_spring[st.fi][st.se] + m) << endl; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> using namespace std; int main(){ int w,h; cin>>w>>h; vector<string> c(h); const long long int INF=1e15; vector<vector<long long int>> spr(h,vector<long long int>(w,INF)); queue<pair<int,int>> que; pair<int,int> s; pair<int,int> g; for(int i=0;i<h;i++){ cin>>c[i]; for(int j=0;j<w;j++){ if(c[i][j]=='s'){ s={i,j}; c[i][j]='.'; } if(c[i][j]=='g'){ g={i,j}; } if(c[i][j]=='*'){ spr[i][j]=0; que.push({i,j}); } } } int dh[]={1,-1,0,0}; int dw[]={0,0,1,-1}; while(!que.empty()){ auto p=que.front(); que.pop(); for(int i=0;i<4;i++){ int th=p.first+dh[i]; int tw=p.second+dw[i]; if(c[th][tw]=='.' && spr[p.first][p.second]+1<spr[th][tw]){ spr[th][tw]=spr[p.first][p.second]+1; que.push({th,tw}); } } } vector<vector<long long int>> goal(h,vector<long long int>(w,INF)); goal[g.first][g.second]=0; que.push({g.first,g.second}); while(!que.empty()){ auto p=que.front(); que.pop(); for(int i=0;i<4;i++){ int th=p.first+dh[i]; int tw=p.second+dw[i]; if(c[th][tw]=='.' && goal[p.first][p.second]+1<goal[th][tw]){ goal[th][tw]=goal[p.first][p.second]+1; que.push({th,tw}); } } } int fcnt=0; long long int sum1=0; long long int sum2=0; vector<pair<long long int,pair<int,int>>> ex; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(c[i][j]=='.'){ fcnt++; if(!(goal[i][j]!=INF || spr[i][j]!=INF)){ cout<<goal[s.first][s.second]<<endl; return 0; } long long int dis=goal[i][j]-spr[i][j]; if(dis<=0){ sum1+=goal[i][j]; } else{ sum2+=spr[i][j]; ex.push_back({dis,{i,j}}); } } } } sort(ex.begin(),ex.end()); double resex=-1; int inde=0; for(int x=1;x<=1000000;x++){//ex=[x,x+1) for(;inde<ex.size();inde++){ if(ex[inde].first<=x){ int i=ex[inde].second.first; int j=ex[inde].second.second; sum1+=goal[i][j]; sum2-=spr[i][j]; } else{ break; } } const double EPS=1e-12; if(ex.size()==inde){ double xa=double(sum1)/fcnt; if(x-EPS<xa){ resex=xa; } break; } double xa=double(sum1+sum2)/fcnt/(1-(double(ex.size()-inde)/fcnt)); if(x-EPS<xa && xa<=x+1-EPS || (x==1000000 && x-EPS<xa)){ assert(resex==-1); resex=xa; } } assert(resex!=-1); cout<<fixed<<setprecision(10); cout<<min<double>(goal[s.first][s.second],spr[s.first][s.second]+resex)<<endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <queue> #include <string> #include <iomanip> #include <iostream> #pragma warning(disable : 4996) using namespace std; struct state { int x, y; long double dist; }; bool operator<(const state& s1, const state& s2) { return s1.dist < s2.dist; } int dir[4] = { 0, 1, 0, -1 }; int H, W, sx, sy; long double dist[555][555]; string s[555]; int main() { cin >> W >> H; for (int i = 0; i < H; i++) { cin >> s[i]; if (s[i].find('s') != string::npos) { sx = i; sy = s[i].find('s'); } } long double l = 0.0, r = 1.0e+10; for (int i = 0; i < 80; i++) { long double m = (l + r) * 0.5; priority_queue<state> que; for (int j = 0; j < H; j++) { for (int k = 0; k < W; k++) { dist[j][k] = 1.0e+15; if (s[j][k] == 'g') { dist[j][k] = 0.0; que.push(state{ j, k, 0.0 }); } if (s[j][k] == '*') { dist[j][k] = m; que.push(state{ j, k, -m }); } } } while (!que.empty()) { state u = que.top(); que.pop(); for (int i = 0; i < 4; i++) { int tx = u.x + dir[i], ty = u.y + dir[i ^ 1]; if (0 <= tx && tx < H && 0 <= ty && ty < W && s[tx][ty] != '#' && s[tx][ty] != '*' && dist[tx][ty] > dist[u.x][u.y] + 1.0L) { dist[tx][ty] = dist[u.x][u.y] + 1.0L; que.push(state{ tx, ty, -dist[tx][ty] }); } } } long double sum = 0.0; int cnt = 0; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (s[i][j] == 's' || s[i][j] == '.') { sum += dist[i][j]; cnt++; } } } if (sum < m * cnt) r = m; else l = m; } cout << fixed << setprecision(10) << dist[sx][sy] << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace std; const long long INF = 1LL<<40; void minDist(const vector<string>& plane, char start, vector<vector<long long> >& dist) { int dy[] = {0, 0, -1, 1}; int dx[] = {-1, 1, 0, 0}; int h = plane.size(); int w = plane[0].size(); dist.assign(h, vector<long long>(w, INF)); queue<pair<int, int> > q; for(int i=0; i<h; ++i){ for(int j=0; j<w; ++j){ if(plane[i][j] == start) q.push(make_pair(i, j)); } } int n = 1; while(!q.empty()){ queue<pair<int, int> > q1; while(!q.empty()){ int y = q.front().first; int x = q.front().second; q.pop(); for(int i=0; i<4; ++i){ int y1 = y + dy[i]; int x1 = x + dx[i]; if(0 <= y1 && y1 < h && 0 <= x1 && x1 < w && plane[y1][x1] == '.' && dist[y1][x1] == INF){ q1.push(make_pair(y1, x1)); dist[y1][x1] = n; } } } ++ n; q = q1; } } int main() { int w, h; cin >> w >> h; vector<string> c(h); vector<vector<bool> > floor(h, vector<bool>(w, false)); int n = 0; // 床の数 int sy, sx; // スタート位置 for(int i=0; i<h; ++i){ cin >> c[i]; for(int j=0; j<w; ++j){ if(c[i][j] == 's'){ sy = i; sx = j; c[i][j] = '.'; } if(c[i][j] == '.'){ floor[i][j] = true; ++ n; } } } vector<vector<long long> > a, b; // ゴールまでの距離、バネまでの距離 minDist(c, 'g', a); minDist(c, '*', b); multiset<long long> diff; long long sum = 0; for(int i=0; i<h; ++i){ for(int j=0; j<w; ++j){ if(!floor[i][j]) continue; sum += b[i][j]; diff.insert(a[i][j] - b[i][j]); } } double ret = a[sy][sx]; for(int i=0; i<n; ++i){ sum += *diff.begin(); diff.erase(diff.begin()); ret = min(ret, b[sy][sx] + sum / (i + 1.0)); } printf("%.10f\n", ret); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
// #ifdef DEBUG // #define _GLIBCXX_DEBUG // #endif #include <iostream> #include <cassert> #include <iomanip> #include <vector> #include <valarray> #include <map> #include <set> #include <list> #include <queue> #include <stack> #include <bitset> #include <utility> #include <numeric> #include <algorithm> #include <functional> #include <complex> #include <string> #include <sstream> #include <cstdio> #include <cstdlib> #include <cctype> #include <cstring> // these require C++11 #include <unordered_set> #include <unordered_map> #include <random> #include <thread> #include <chrono> #include <tuple> using namespace std; #define int long long #define all(c) c.begin(), c.end() #define repeat(i, n) for (int i = 0; i < static_cast<int>(n); i++) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define dump(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define dump(x) #endif template<typename A,typename B> ostream &operator<<(ostream&os,const pair<A,B>& p){ os << "(" << p.first << "," << p.second << ")"; return os; } typedef complex<double> point; // template<typename T,std::size_t N> // struct _v_traits {using type = std::vector<typename _v_traits<T,N-1>::type>;}; // template<typename T> // struct _v_traits<T,1> {using type = std::vector<T>;}; // template<typename T,std::size_t N=1> // using vec = typename _v_traits<T,N>::type; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } const int INF = 1000000000000ll; struct Info { int to_goal; int to_spring; bool is_start; }; ostream &operator<<(ostream &os, const Info &i) { return os << "(" << i.to_goal << "," << i.to_spring << ")"; } const char wall = '#'; const char spring = '*'; const char dot = '.'; const char start = 's'; const char goal = 'g'; const vector<int> dx = {-1,0,1,0}; const vector<int> dy = {0, 1,0,-1}; // ?????¢??°????\???§??????????????¨?????? template<typename F,typename T> T ternary_search(F f,T left,T right,int try_cnt = 1000){ for(int i=0;i<try_cnt;i++){ T l = (2*left + right) / 3; T r = (left + 2*right) / 3; if(f(l) < f(r)){ left = l; }else{ right = r; } } return (left+right)/2; } // ?????¢??°????\??°???????????±??????? template<typename F,typename T> T ternary_search_concave(F f,T left,T right,int try_cnt=1000){ return ternary_search([f](T x){return -f(x);},left,right); } // [0 ~ k) /*long double calc_e(const vector<Info>& v, const vector<int>& as, const vector<int>& bs, const int k, const int s=0){ const int N = v.size(); int l = as[k]; int r = bs[N] - bs[k]; if(s > 1000) return 1.0F * (l+r) / N; return (l + r + (1.0F * (N-k) * calc_e(v,as,bs,k,s+1)))/N; }*/ double target(const vector<Info>& dots, double e) { double t = 0.0; for (const auto & i : dots) { t += min((double)i.to_spring, i.to_goal - e); } return t; } signed main() { ios::sync_with_stdio(false); cin.tie(0); int W,H; cin >> W >> H; vector<string> field(H); for(string& s : field){ cin >> s; } vector<vector<Info> > info(H,vector<Info>(W,Info{INF,INF,false})); for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(field[i][j] == start) info[i][j].is_start = true; } } for(int to_finding_spring=0;to_finding_spring<2;to_finding_spring++){ // value,y,x queue<tuple<int,int,int> > queue; set<tuple<int,int> > already; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if((to_finding_spring and field[i][j] == spring) or (!to_finding_spring and field[i][j] == goal)){ queue.emplace(0,i,j); } } } while(not queue.empty()){ auto t = queue.front(); queue.pop(); int v = get<0>(t); int y = get<1>(t); int x = get<2>(t); if(already.find(make_tuple(y,x)) != already.end()){ continue; } if(to_finding_spring && (field[y][x] == wall or field[y][x] == goal)){ continue; } if(not to_finding_spring && (field[y][x] == wall or field[y][x] == spring)){ continue; } already.insert(make_tuple(y,x)); if(to_finding_spring){ info[y][x].to_spring = v; }else{ info[y][x].to_goal = v; } for(int i=0;i<4;i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(0 <= nx and nx < W and 0 <= ny and ny < H and already.find(make_tuple(ny,nx)) == already.end()){ queue.emplace(v+1,ny,nx); } } } } /* {info[i][j] |-> ??´???????????§????????¢?????´?????????????????§????????¢} */ vector<Info> dots; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(field[i][j] == dot || field[i][j] == start){ if (info[i][j].to_goal > INF / 2 && info[i][j].to_spring > INF / 2) {continue;} dots.push_back(info[i][j]); } } } /* dots???????????§?£?????????´?????¨??????info?????\?????? */ double minimum = 0, maximum = 1e15; // assert (target(dots, minimum) > 0); // dump(dots); // dump(target(dots, maximum)); // assert (target(dots, maximum) < 0); for (int i = 0; i < 500; i++) { double half = (minimum + maximum) / 2.; double val = target(dots, half); // dump(half); // dump(val); if (val > 0) { minimum = half; } else { maximum = half; } } dump(minimum); auto si = find_if(dots.begin(),dots.end(),[](const Info& i){return i.is_start;}); cout << fixed << setprecision(12); cout << min(si->to_spring + minimum, (double)si->to_goal) << endl; return 0; /* sort(dots.begin(),dots.end(),[](const Info& left,const Info& right){ int l = left.to_goal - left.to_spring; int r = right.to_goal - right.to_spring; return l < r; }); int si = find_if(dots.begin(),dots.end(),[](const Info& i){return i.is_start;}) - dots.begin(); int N = dots.size(); vector<int> as(N+1); vector<int> bs(N+1); for(int i=1;i<N+1;i++){ as[i] = as[i-1] + dots[i-1].to_goal; bs[i] = bs[i-1] + dots[i-1].to_spring; } // dump(bs[N]); // dump(as[N]); // dump((long double)(as[si+1] - as[si])); // dump((long double)(bs[si+1] - bs[si])); auto f = [&](long double c){ int k = 0; for(k=0;k<N;k++){ if(dots[k].to_goal - dots[k].to_spring > c + 1e-9){ break; } } if(si < k){ return (long double)(as[si+1]-as[si]); }else{ return (bs[si+1] - bs[si]) + calc_e(dots,as,bs,k); } }; int ls = as[1] - bs[1]; int rs = as[N] - as[N-1] - (bs[N] - bs[N-1]); auto r = ternary_search_concave(f,ls,rs); // for(int i=0;i<N;i++){ // double d = as[i+1] - as[i] - (bs[i+1] - bs[i]); // cerr << d << " -> " << f(d) << endl; // } cout << fixed << setprecision(12); cout << f(r) << endl; return 0; */ }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <vector> #include <map> #include <queue> #include <tuple> #include <functional> #include <cstdio> #include <cmath> #define repeat(i,n) for (int i = 0; (i) < (n); ++(i)) template <class T> bool setmax(T & l, T const & r) { if (not (l < r)) return false; l = r; return true; } template <class T> bool setmin(T & l, T const & r) { if (not (r < l)) return false; l = r; return true; } using namespace std; const int inf = 1e9+7; const int dy[] = { -1, 1, 0, 0 }; const int dx[] = { 0, 0, 1, -1 }; int main() { // input int w, h; cin >> w >> h; vector<string> c(h); repeat (y,h) cin >> c[y]; // modify input int sy, sx, gy, gx; repeat (y,h) repeat (x,w) { if (c[y][x] == 's') { sy = y; sx = x; c[y][x] = '.'; } else if (c[y][x] == 'g') { gy = y; gx = x; } } // prepare auto on_field = [&](int y, int x) { return 0 <= y and y < h and 0 <= x and x < w; }; typedef queue<pair<int,int> > points_queue; auto bfs = [&](function<void (points_queue &)> init, function<void (points_queue &, int, int, int, int)> update) { points_queue que; init(que); while (not que.empty()) { int y, x; tie(y, x) = que.front(); que.pop(); repeat (i,4) { int ny = y + dy[i]; int nx = x + dx[i]; if (not on_field(ny, nx)) continue; if (c[ny][nx] != '.') continue; update(que, y, x, ny, nx); } } }; vector<vector<int> > goal(h, vector<int>(w, inf)); bfs([&](points_queue & que) { goal[gy][gx] = 0; que.push(make_pair(gy, gx)); }, [&](points_queue & que, int y, int x, int ny, int nx) { if (goal[ny][nx] == inf) { goal[ny][nx] = goal[y][x] + 1; que.push(make_pair(ny, nx)); } }); vector<vector<int> > jump(h, vector<int>(w, inf)); bfs([&](points_queue & que) { repeat (y,h) repeat (x,w) if (c[y][x] == '*') { jump[y][x] = 0; que.push(make_pair(y, x)); } }, [&](points_queue & que, int y, int x, int ny, int nx) { if (jump[ny][nx] == inf) { jump[ny][nx] = jump[y][x] + 1; que.push(make_pair(ny, nx)); } }); map<pair<int,int>,int> freq; // frequency int total = 0; int max_goal = 0; repeat (y,h) repeat (x,w) if (c[y][x] == '.') { freq[make_pair(goal[y][x], jump[y][x])] += 1; total += 1; if (goal[y][x] < inf) setmax(max_goal, goal[y][x]); } // calc long double e = INFINITY; repeat (estimate, max_goal + 1) { // E = f(E) = aE + b long double a = 0; long double b = 0; for (auto it : freq) { int g, j; tie(g, j) = it.first; int cnt = it.second; long double p = cnt /(long double) total; if (g == inf) { a += p; b += p * j; } else if (j == inf) { b += p * g; } else { if (g <= j + estimate) { b += p * g; } else { a += p; b += p * j; } } } setmin(e, b / (1 - a)); } // output long double ans = goal[sy][sx] == inf ? jump[sy][sx] + e : jump[sy][sx] == inf ? goal[sy][sx] : min<long double>(goal[sy][sx], jump[sy][sx] + e); // the answer can become grater than `int inf`, so conditional op. is required. printf("%.12Lf\n", ans); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repl(i,0,n) #define mp(a,b) make_pair((a),(b)) #define pb(a) push_back((a)) #define all(x) (x).begin(),(x).end() #define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x)) #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} #define INF 21474836001234567 #define double long double int main(){ int w,h; cin>>w>>h; vector<string> vec(h); rep(i,h) cin>>vec[i]; int sx,sy,tx,ty; vector<int> spx,spy; rep(i,h)rep(j,w){ if(vec[i][j]=='s') sx=i,sy=j; if(vec[i][j]=='g') tx=i,ty=j; if(vec[i][j]=='*') spx.pb(i), spy.pb(j); } vector<vector<long>> d(h, vector<long>(w, INF)); // g?????§??????????????¢ { queue<int> xs,ys; d[tx][ty] = 0; xs.push(tx); ys.push(ty); while(!xs.empty()){ int x = xs.front(); xs.pop(); int y = ys.front(); ys.pop(); const int dx[] = {0,0,-1,1}, dy[] = {-1,1,0,0}; rep(i,4){ int nx = x+dx[i]; int ny = y+dy[i]; if(vec[nx][ny]!='#' && vec[nx][ny]!='*' && d[nx][ny]>d[x][y]+1){ d[nx][ny] = d[x][y]+1; xs.push(nx); ys.push(ny); } } } } vector<vector<long>> ds(h,vector<long>(w,INF)); // ????????????spring?????§??????????????¢ { queue<int> xs,ys; rep(i,spx.size()){ xs.push(spx[i]); ys.push(spy[i]); ds[spx[i]][spy[i]] = 0; } while(!xs.empty()){ int x = xs.front(); xs.pop(); int y = ys.front(); ys.pop(); const int dx[] = {0,0,-1,1}, dy[] = {-1,1,0,0}; rep(i,4){ int nx = x+dx[i]; int ny = y+dy[i]; if(vec[nx][ny]!='#' && vec[nx][ny]!='*' && ds[nx][ny]>ds[x][y]+1){ ds[nx][ny] = ds[x][y]+1; xs.push(nx); ys.push(ny); } } } } double p = INF; // ????????§?£???°??????????????¨?????????????§???????????????? { int cnt=1; rep(i,h)rep(j,w)if(vec[i][j]=='.') cnt++; double l = 0, r = 500.0*500*500*500; rep(_,1000){ double m = (l+r)/2.0; double accm = min<double>(d[sx][sy], ds[sx][sy]+m); rep(i,h) rep(j,w)if(vec[i][j]=='.'){ accm += min<double>(d[i][j], ds[i][j]+m); } p = accm/cnt; if(p<m) r = m; else l = m; } p = (r+l)/2.0; } printf("%.10Lf\n", min<double>(d[sx][sy], ds[sx][sy]+p)); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<iostream> #include<algorithm> #include<queue> #include<tuple> using namespace std; #define int long long char c[523][523]; template<class A> void bfs(A &ds,queue<tuple<int,int,int> > que){ fill(*begin(ds),*end(ds),1e9); while(!que.empty()){ auto cs=que.front(); que.pop(); int t=get<0>(cs); int y=get<1>(cs); int x=get<2>(cs); if(ds[y][x]<=t)continue; ds[y][x]=t; for(int i=0;i<4;i++){ static const int d[]={0,1,0,-1,0}; int ny=y+d[i]; int nx=x+d[i+1]; if(c[ny][nx]=='.'){ que.push(make_tuple(t+1,ny,nx)); } } } } signed main(){ int W,H; cin>>W>>H; queue<tuple<int,int,int> > sque,gque; int sy,sx; int n=0; for(int i=0;i<H;i++){ cin>>c[i]; for(int j=0;j<W;j++){ if(c[i][j]=='s'){ c[i][j]='.'; sy=i; sx=j; }else if(c[i][j]=='*'){ sque.push(make_tuple(0,i,j)); }else if(c[i][j]=='g'){ gque.push(make_tuple(0,i,j)); } n+=c[i][j]=='.'; } } static int ds[523][523]; bfs(ds,sque); static int dg[523][523]; bfs(dg,gque); int gsum=0,ssum=0; int xsum=0; int gs[2555]={},ss[2555]={}; int xs[2555]={}; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(c[i][j]=='.'){ int cx=min<int> (2500,max<int>(0,dg[i][j]-ds[i][j])); gsum+=dg[i][j]; gs[cx]+=dg[i][j]; ss[cx]+=ds[i][j]; xs[cx]++; } } } double ans=1e18; for(int i=2500;i>=0;i--){ gsum-=gs[i]; ssum+=ss[i]; xsum+=xs[i]; if(xsum==n)continue; ans=min(ans,(dg[sy][sx]-ds[sy][sx]>=i)?ds[sy][sx]+(gsum+ssum)*1./(n-xsum):dg[sy][sx]); } cout.precision(99); cout<<fixed<<ans<<endl; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <queue> #include <iomanip> #include <iostream> #include <vector> #include <string> #include <map> #include <algorithm> #include <tuple> #define REP(i,n) for(int i=0;i<(int)(n);i++) using namespace std; typedef long long Weight; const Weight INF = 1000000000000ll; struct Edge{ int src, dest; Weight weight; bool operator < (const Edge &rhs) const {return weight > rhs.weight;} }; typedef vector<Edge> Edges; typedef vector<Edges> Graph; typedef vector<Weight> Array; typedef vector<Array> Matrix; // The costs of edges must be 0 or 1 (Verified: TCO 2014 Round 2C Medium) void bfs01(Graph &g, vector<Weight> &d, int s) { fill(d.begin(), d.end(), INF); d[s] = 0; typedef pair<Weight,int> P; queue<P> que, zero; que.push(P(0, s)); while (!zero.empty() || !que.empty()) { P top = zero.empty() ? que.front() : zero.front(); if (zero.empty()) que.pop(); else zero.pop(); Weight dist = top.first; int v = top.second; if (d[v] < dist) continue; REP(i, g[v].size()) { Edge e = g[v][i]; if (d[e.dest] > d[v] + e.weight) { d[e.dest] = d[v] + e.weight; if (e.weight) que.push(P(d[e.dest], e.dest)); else zero.push(P(d[e.dest], e.dest)); } } } } bool is_mbl(char c){ return c=='.'||c=='s'||c=='g'||c=='*'; } bool is_bembl(char c){ return c=='.'||c=='s'; } int main() { int w,h; cin>>w>>h; vector<string> t(h); REP(i,h)cin>>t[i]; int s,gix; REP(i,h)REP(j,w){ if(t[i][j]=='s'){ s=i*w+j; }else if(t[i][j]=='g'){ gix=i*w+j; } } Graph g(h*w+1); REP(i,h)REP(j,w){ if(!is_mbl(t[i][j]))continue; int di[]={1,0,-1,0}; int dj[]={0,1,0,-1}; int six = i*w+j; REP(k,4){ int ni=i+di[k]; int nj=j+dj[k]; if(ni<0||nj<0||ni>=h||nj>=w)continue; if(!is_bembl(t[ni][nj]))continue; int tix = ni*w+nj; g[six].push_back({six,tix,1}); } if(t[i][j]=='*'){ g[h*w].push_back({h*w,six,0}); } } Array dg(h*w+1); Array ds(h*w+1); bfs01(g, dg, gix); bfs01(g, ds, h*w); long double v=1e+10; long double ex_spr = 0; while(v > 1e-14){ long double dist_sum = 0; int cnt=0; REP(i,h*w){ if(!is_bembl(t[i/w][i%w]))continue; dist_sum += min((long double)(dg[i]), ds[i] + ex_spr + v); ++cnt; } if (ex_spr + v < (dist_sum/cnt)) { ex_spr += v; } v /= 2.0; } cout << setprecision(14) << fixed << min((long double)(dg[s]), ds[s] + ex_spr) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)(n); ++i) #define REP(i,n) FOR(i,0,n) #define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cerr<<*i<<" "; cerr<<endl; } inline bool valid(int x, int y, int W, int H){ return (x >= 0 && y >= 0 && x < W && y < H); } typedef long long ll; const double INF = 1e18; int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1}; int W, H; void bfs(double dist[500][500], int sx, int sy, string grid[500]){ queue<int> qx, qy; qx.push(sx); qy.push(sy); dist[sy][sx] = 0; while(!qx.empty()){ int x = qx.front(), y = qy.front(); qx.pop(); qy.pop(); REP(r, 4){ int nx = x + dx[r], ny = y + dy[r]; if(valid(nx, ny, W, H) && grid[ny][nx] == '.'){ if(dist[ny][nx] == -1.0 || dist[ny][nx] > dist[y][x] + 1){ dist[ny][nx] = dist[y][x] + 1; qx.push(nx); qy.push(ny); } } } } } int main(){ while(cin >> W >> H && W){ string grid[500]; REP(i, H) cin >> grid[i]; int sx, sy; REP(y, H) REP(x, W) if(grid[y][x] == 's') { sx = x, sy = y; grid[y][x] = '.'; } int N = 0; REP(y, H) REP(x, W) if(grid[y][x] == '.') N++; double dist_goal[500][500], dist_spring[500][500]; REP(y, H) REP(x, W) dist_goal[y][x] = dist_spring[y][x] = -1.0; REP(y, H) REP(x, W) if(grid[y][x] == 'g') bfs(dist_goal, x, y, grid); REP(y, H) REP(x, W) if(grid[y][x] == '*') bfs(dist_spring, x, y, grid); REP(y, H) REP(x, W) if(dist_goal[y][x] == -1) dist_goal[y][x] = INF; REP(y, H) REP(x, W) if(dist_spring[y][x] == -1) dist_spring[y][x] = INF; double lb = 0, ub = 1e18; REP(_, 100){ const long double sum = (ub + lb) * 0.5; long double S = 0; REP(y, H) REP(x, W)if(grid[y][x] == '.'){ long double exp = min((long double)dist_goal[y][x], dist_spring[y][x] + sum / N); S += exp; } if(sum - S > 0){ ub = sum; }else{ lb = sum; } } double all_exp = lb / N; printf("%.12f\n", min((double)dist_goal[sy][sx], dist_spring[sy][sx] + all_exp)); } return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <cstdio> #include <utility> #include <queue> #include <iostream> using namespace std; int main(){ int W, H, gx, gy, sx, sy, n = 0; cin >> W >> H; string M[H]; vector< pair<int,int> > springs; for(int i = 0; i < H; ++i){ cin >> M[i]; for(int j = 0; j < W; ++j){ if(M[i][j] == 'g'){ gx = i; gy = j; M[i][j] = '.'; }else if(M[i][j] == 's'){ sx = i; sy = j; M[i][j] = '.'; ++n; }else if(M[i][j] == '.') ++n; else if(M[i][j] == '*'){ springs.push_back(make_pair(i,j)); } } } long double INF = (1e10), l = 0.0, r = INF, exp_[H][W], exp[H][W]; int d[] = {1,0,-1,0}; queue< pair<int,int> > que; que.push(make_pair(gx,gy)); for(int i = 0; i < H; ++i){ for(int j = 0; j < W; ++j){ exp_[i][j] = INF; exp[i][j] = INF; } } exp_[gx][gy] = 0.0; while(!que.empty()){ int x = que.front().first, y = que.front().second; que.pop(); for(int k = 0; k < 4; ++k){ int x_ = x + d[k], y_ = y + d[(k+1)%4]; if(x_ >= H || x_ < 0 || y_ >= W || y_ < 0) continue; char c = M[x_][y_]; if(c == '.' && exp_[x_][y_] > exp_[x][y]+1){ exp_[x_][y_] = exp_[x][y]+1; que.push(make_pair(x_,y_)); } } } /* long double dist_from_spring[H][W]; for(int i = 0; i < H; ++i){ for(int j = 0; j < W; ++j){ dist_from_spring[i][j] = INF; } } */ vector< vector<long double> > dist_from_spring(H, vector<long double>(W, INF)); for(int i = 0; i < springs.size(); ++i){ queue< pair<int,int> > que2; que2.push(make_pair(springs[i].first, springs[i].second)); dist_from_spring[springs[i].first][springs[i].second] = 0; while(!que2.empty()){ int x = que2.front().first, y = que2.front().second; que2.pop(); for(int k = 0; k < 4; ++k){ int x_ = x + d[k], y_ = y + d[(k+1)%4]; if(x_ >= H || x_ < 0 || y_ >= W || y_ < 0) continue; char c = M[x_][y_]; if(c == '.' && (dist_from_spring[x_][y_] > dist_from_spring[x][y]+1)){ que2.push(make_pair(x_,y_)); dist_from_spring[x_][y_] = dist_from_spring[x][y]+1; } } } } for(int t = 0; t < 100; ++t){ long double mean = (l+r)/2.0; long double s = 0.0; for(int i = 0; i < H; ++i){ for(int j = 0; j < W; ++j){ if(M[i][j] == '.'){ exp[i][j] = min(exp_[i][j], dist_from_spring[i][j]+mean); s += exp[i][j]; } } } if(s/n < mean){ r = mean; }else{ l = mean; } } printf("%.12Lf\n",exp[sx][sy]); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <algorithm> #include <climits> #include <functional> #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; typedef long long ll; typedef pair<int, int> i_i; struct edge { int v, w; }; ll INF = LLONG_MAX / 2; int dy[] = {0, -1, 0, 1}; int dx[] = {-1, 0, 1, 0}; int main() { int H, W; cin >> W >> H; vector<string> a(H); for (int y = 0; y < H; y++) cin >> a[y]; int ys, xs, yg, xg; for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) { if (a[y][x] == 's') { a[y][x] = '.'; ys = y; xs = x; } if (a[y][x] == 'g') { yg = y; xg = x; } } vector<vector<ll> > dg(H, vector<ll>(W, INF)); queue<i_i> q; dg[yg][xg] = 0; q.push(i_i(yg, xg)); while (q.size()) { i_i p = q.front(); q.pop(); int y = p.first, x = p.second; for (int k = 0; k < 4; k++) { int _y = y + dy[k], _x = x + dx[k]; if (a[_y][_x] == '.' && dg[_y][_x] > dg[y][x] + 1) { dg[_y][_x] = dg[y][x] + 1; q.push(i_i(_y, _x)); } } } vector<vector<ll> > ds(H, vector<ll>(W, INF)); for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) if (a[y][x] == '*') { ds[y][x] = 0; q.push(i_i(y, x)); } while (q.size()) { i_i p = q.front(); q.pop(); int y = p.first, x = p.second; for (int k = 0; k < 4; k++) { int _y = y + dy[k], _x = x + dx[k]; if (a[_y][_x] == '.' && ds[_y][_x] > ds[y][x] + 1) { ds[_y][_x] = ds[y][x] + 1; q.push(i_i(_y, _x)); } } } long double lb = 0, ub = 1e15; for (int t = 0; t < 100; t++) { long double mid = (lb + ub) / 2; int k = 0; long double sum = 0; for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) if (a[y][x] == '.') { k++; sum += min((long double)dg[y][x], ds[y][x] + mid); } if (sum / k > mid) lb = mid; else ub = mid; } double ans = min((long double)dg[ys][xs], ds[ys][xs] + lb); printf("%.15f\n", ans); }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <string> #include <map> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const long double EPS = 1e-9; static const long double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) struct Point { int x, y, cost; Point() {;} Point(int x, int y, int cost) : x(x), y(y), cost(cost) {;} }; int w, h; char field[600][600]; int springDist[600][600]; int goalDist[600][600]; const int dx[4] = { 1, 0, -1, 0 }; const int dy[4] = { 0, 1, 0, -1 }; int sx, sy; inline bool Movable(int x, int y) { if (x < 0 || x >= w || y < 0 || y >= h) { return false; } if (field[y][x] != '.') { return false; } return true; } void CalcDist() { MEMSET(springDist, -1); MEMSET(goalDist, -1); queue<Point> que; REP(y, h) { REP(x, w) { if (field[y][x] == '*') { REP(dir, 4) { int nx = x + dx[dir]; int ny = y + dy[dir]; if (!Movable(nx, ny)) { continue; } que.push(Point(nx, ny, 1)); } } } } while (!que.empty()) { Point p = que.front(); que.pop(); if (springDist[p.y][p.x] != -1) { continue; } springDist[p.y][p.x] = p.cost; REP(dir, 4) { int nx = p.x + dx[dir]; int ny = p.y + dy[dir]; if (!Movable(nx, ny)) { continue; } que.push(Point(nx, ny, p.cost + 1)); } } REP(y, h) { REP(x, w) { if (field[y][x] == 'g') { que.push(Point(x, y, 0)); } } } while (!que.empty()) { Point p = que.front(); que.pop(); if (goalDist[p.y][p.x] != -1) { continue; } goalDist[p.y][p.x] = p.cost; REP(dir, 4) { int nx = p.x + dx[dir]; int ny = p.y + dy[dir]; if (!Movable(nx, ny)) { continue; } que.push(Point(nx, ny, p.cost + 1)); } } } long double ToGoal(int x, int y, long double E) { long double ret = 1e+100; if (goalDist[y][x] != -1) { ret = min(ret, (long double)goalDist[y][x]); } if (springDist[y][x] != -1) { ret = min(ret, springDist[y][x] + E); } //cout << x << " " << y << endl; assert(goalDist[y][x] != -1 || springDist[y][x] != -1); return ret; } //long double vs[510 * 510]; long double calc(long double E) { long double nE = 0.0; int cnt = 0; //priority_queue<long double> que; REP(y, h) { REP(x, w) { if (field[y][x] != '.') { continue; } //vs[cnt++] = ToGoal(x, y, E); //que.push(-ToGoal(x, y, E)); nE += ToGoal(x, y, E); cnt++; } } //sort(vs, vs + cnt); //REP(i, cnt - 1) { //nE += vs[i]; //long double l = que.top(); //que.pop(); //long double r = que.top(); //que.pop(); //que.push(l + r); //} return nE / cnt; } int main() { while (scanf("%d %d", &w, &h) > 0) { REP(y, h) { scanf("%s", field[y]); REP(x, w) { if (field[y][x] == 's') { sx = x; sy = y; field[y][x] = '.'; } } } CalcDist(); long double left = 1.0; long double right = 1e+10; if (springDist[sy][sx] != -1) { REP(iter, 80) { long double mid = (left + right) / 2.0; if (calc(mid) > mid) { left = mid; } else { right = mid; } } } printf("%.10Lf\n", ToGoal(sx, sy, left)); } }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; namespace { typedef long double real; typedef long long ll; template<class T> ostream& operator<<(ostream& os, const vector<T>& vs) { if (vs.empty()) return os << "[]"; os << "[" << vs[0]; for (int i = 1; i < vs.size(); i++) os << " " << vs[i]; return os << "]"; } template<class T> istream& operator>>(istream& is, vector<T>& vs) { for (auto it = vs.begin(); it != vs.end(); it++) is >> *it; return is; } int W, H; vector<string> F; void input() { cin >> W >> H; F.clear(); F.resize(H); cin >> F; } const real INF = 1e200; const int dy[] = {0, -1, 0, 1}; const int dx[] = {-1, 0, 1, 0}; vector< vector<real> > C; // from the stairs vector< vector<real> > S; // from the nearest spring; void bfs(int sy, int sx, vector< vector<real> >& M) { assert(M.size() == H && M[0].size() == W); queue< pair<int, int> > Q; Q.push(make_pair(sy, sx)); M[sy][sx] = 0; while (not Q.empty()) { auto cur = Q.front(); Q.pop(); int cy = cur.first, cx = cur.second; for (int i = 0; i < 4; i++) { int ny = cy + dy[i], nx = cx + dx[i]; if (ny < 0 || ny >= H) continue; if (nx < 0 || nx >= W) continue; if (F[ny][nx] == '#') continue; if (F[ny][nx] == '*') continue; real ncost = M[cy][cx] + 1; if (M[ny][nx] > ncost) { M[ny][nx] = ncost; Q.push(make_pair(ny, nx)); } } } } int N; int X, Y; void init() { N = 0; C = vector< vector<real> >(H, vector<real>(W, INF)); S = vector< vector<real> >(H, vector<real>(W, INF)); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (F[i][j] == 'g') { bfs(i, j, C); } else if (F[i][j] == '*') { bfs(i, j, S); } else if (F[i][j] == 's' || F[i][j] == '.') { if (F[i][j] == 's') { Y = i; X = j; } N++; } else { assert(F[i][j] == '#'); } } } } real f(real x) { real ret = 0; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (F[i][j] == '.' || F[i][j] == 's') { ret += min(S[i][j] + x, C[i][j]); } } } return ret / N; } real g(real x) { return x - f(x); } void solve() { init(); real lb = 0, ub = INF; for (int i = 0; i < 1000; i++) { //if (i % 100 == 0) cerr << i << endl; real mid = (lb + ub) / 2; (g(mid) < 0 ? lb : ub) = mid; } real x = lb; //cerr << "x: " << x << endl; //cerr << S[Y][X] << endl; cout << fixed << setprecision(12) << min(C[Y][X], S[Y][X] + x) << endl; } } int main() { input(); solve(); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #define mmax(x,y) (x>y?x:y) #define mmin(x,y) (x<y?x:y) #define maxch(x,y) x=mmax(x,y) #define minch(x,y) x=mmin(x,y) #define uni(x) x.erase(unique(all(x)),x.end()) #define exist(x,y) (find(all(x),y)!=x.end()) #define bcnt __builtin_popcountll #define INF 1e16 #define mod 1000000007 int W,H; string s[500]; ll a[500][500]; ll b[500][500]; int dd[]={-1,0,1,0,-1}; int si,sj; vector<P> ts; int main(){ cin.tie(0); ios::sync_with_stdio(false); cin>>W>>H; rep(i,H)cin>>s[i]; rep(i,H)rep(j,W){ if(s[i][j]=='s'){ si=i; sj=j; } } rep(i,H)rep(j,W)a[i][j]=b[i][j]=INF; { queue<P> que; rep(i,H)rep(j,W){ if(s[i][j]=='g'){ que.push(P(i,j)); a[i][j]=0; } } while(que.size()){ P p=que.front(); que.pop(); rep(d,4){ int ni=p.fi+dd[d],nj=p.se+dd[d+1]; if(ni<0||ni>=H||nj<0||nj>=W||s[ni][nj]=='#'||s[ni][nj]=='*'||a[ni][nj]!=INF)continue; a[ni][nj]=a[p.fi][p.se]+1; que.push(P(ni,nj)); } } } { queue<P> que; rep(i,H)rep(j,W){ if(s[i][j]=='*'){ que.push(P(i,j)); b[i][j]=0; } } while(que.size()){ P p=que.front(); que.pop(); rep(d,4){ int ni=p.fi+dd[d],nj=p.se+dd[d+1]; if(ni<0||ni>=H||nj<0||nj>=W||s[ni][nj]=='#'||s[ni][nj]=='g'||b[ni][nj]!=INF)continue; b[ni][nj]=b[p.fi][p.se]+1; que.push(P(ni,nj)); } } } rep(i,H)rep(j,W){ if(s[i][j]=='s'||s[i][j]=='.')ts.push_back(P(i,j)); } sort(all(ts),[=](const P& t1,const P& t2){ return a[t1.fi][t1.se]-b[t1.fi][t1.se] < a[t2.fi][t2.se]-b[t2.fi][t2.se]; }); bool oc=true; long double res=a[si][sj]; long double suma=0,sumb=0; ll T=ts.size(); rep(i,T)sumb+=b[ts[i].fi][ts[i].se]; repl(M,1,T+1){ ll i=ts[M-1].fi,j=ts[M-1].se; suma+=a[i][j]; sumb-=b[i][j]; long double sumE=((long double)(T-M)*suma+(long double)T*sumb)/(long double)M; if(s[i][j]=='s')oc=false; if(oc)minch(res,suma/(long double)T+sumE/(long double)T+b[si][sj]); } printf("%.10Lf\n", res); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
// #ifdef DEBUG // #define _GLIBCXX_DEBUG // #endif #include <iostream> #include <cassert> #include <iomanip> #include <vector> #include <valarray> #include <map> #include <set> #include <list> #include <queue> #include <stack> #include <bitset> #include <utility> #include <numeric> #include <algorithm> #include <functional> #include <complex> #include <string> #include <sstream> #include <cstdio> #include <cstdlib> #include <cctype> #include <cstring> // these require C++11 #include <unordered_set> #include <unordered_map> #include <random> #include <thread> #include <chrono> #include <tuple> using namespace std; #define int long long #define all(c) c.begin(), c.end() #define repeat(i, n) for (int i = 0; i < static_cast<int>(n); i++) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define dump(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define dump(x) #endif #define double long double template<typename A,typename B> ostream &operator<<(ostream&os,const pair<A,B>& p){ os << "(" << p.first << "," << p.second << ")"; return os; } typedef complex<double> point; // template<typename T,std::size_t N> // struct _v_traits {using type = std::vector<typename _v_traits<T,N-1>::type>;}; // template<typename T> // struct _v_traits<T,1> {using type = std::vector<T>;}; // template<typename T,std::size_t N=1> // using vec = typename _v_traits<T,N>::type; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } const int INF = 1000000000000ll; struct Info { int to_goal; int to_spring; bool is_start; }; ostream &operator<<(ostream &os, const Info &i) { return os << "(" << i.to_goal << "," << i.to_spring << ")"; } const char wall = '#'; const char spring = '*'; const char dot = '.'; const char start = 's'; const char goal = 'g'; const vector<int> dx = {-1,0,1,0}; const vector<int> dy = {0, 1,0,-1}; // ?????¢??°????\???§??????????????¨?????? template<typename F,typename T> T ternary_search(F f,T left,T right,int try_cnt = 1000){ for(int i=0;i<try_cnt;i++){ T l = (2*left + right) / 3; T r = (left + 2*right) / 3; if(f(l) < f(r)){ left = l; }else{ right = r; } } return (left+right)/2; } // ?????¢??°????\??°???????????±??????? template<typename F,typename T> T ternary_search_concave(F f,T left,T right,int try_cnt=1000){ return ternary_search([f](T x){return -f(x);},left,right); } // [0 ~ k) /*long double calc_e(const vector<Info>& v, const vector<int>& as, const vector<int>& bs, const int k, const int s=0){ const int N = v.size(); int l = as[k]; int r = bs[N] - bs[k]; if(s > 1000) return 1.0F * (l+r) / N; return (l + r + (1.0F * (N-k) * calc_e(v,as,bs,k,s+1)))/N; }*/ double target(const vector<Info>& dots, double e) { double t = 0.0; for (const auto & i : dots) { t += min((double)i.to_spring, i.to_goal - e); } return t; } signed main() { ios::sync_with_stdio(false); cin.tie(0); int W,H; cin >> W >> H; vector<string> field(H); for(string& s : field){ cin >> s; } vector<vector<Info> > info(H,vector<Info>(W,Info{INF,INF,false})); for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(field[i][j] == start) info[i][j].is_start = true; } } for(int to_finding_spring=0;to_finding_spring<2;to_finding_spring++){ // value,y,x queue<tuple<int,int,int> > queue; set<tuple<int,int> > already; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if((to_finding_spring and field[i][j] == spring) or (!to_finding_spring and field[i][j] == goal)){ queue.emplace(0,i,j); } } } while(not queue.empty()){ auto t = queue.front(); queue.pop(); int v = get<0>(t); int y = get<1>(t); int x = get<2>(t); if(already.find(make_tuple(y,x)) != already.end()){ continue; } if(to_finding_spring && (field[y][x] == wall or field[y][x] == goal)){ continue; } if(not to_finding_spring && (field[y][x] == wall or field[y][x] == spring)){ continue; } already.insert(make_tuple(y,x)); if(to_finding_spring){ info[y][x].to_spring = v; }else{ info[y][x].to_goal = v; } for(int i=0;i<4;i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(0 <= nx and nx < W and 0 <= ny and ny < H and already.find(make_tuple(ny,nx)) == already.end()){ queue.emplace(v+1,ny,nx); } } } } /* {info[i][j] |-> ??´???????????§????????¢?????´?????????????????§????????¢} */ vector<Info> dots; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(field[i][j] == dot || field[i][j] == start){ if (info[i][j].to_goal > INF / 2 && info[i][j].to_spring > INF / 2) {continue;} dots.push_back(info[i][j]); } } } /* dots???????????§?£?????????´?????¨??????info?????\?????? */ double minimum = 0, maximum = 1e15; // assert (target(dots, minimum) > 0); // dump(dots); // dump(target(dots, maximum)); // assert (target(dots, maximum) < 0); for (int i = 0; i < 500; i++) { double half = (minimum + maximum) / 2.; double val = target(dots, half); // dump(half); // dump(val); if (val > 0) { minimum = half; } else { maximum = half; } } dump(minimum); auto si = find_if(dots.begin(),dots.end(),[](const Info& i){return i.is_start;}); cout << fixed << setprecision(12); cout << min(si->to_spring + minimum, (double)si->to_goal) << endl; return 0; /* sort(dots.begin(),dots.end(),[](const Info& left,const Info& right){ int l = left.to_goal - left.to_spring; int r = right.to_goal - right.to_spring; return l < r; }); int si = find_if(dots.begin(),dots.end(),[](const Info& i){return i.is_start;}) - dots.begin(); int N = dots.size(); vector<int> as(N+1); vector<int> bs(N+1); for(int i=1;i<N+1;i++){ as[i] = as[i-1] + dots[i-1].to_goal; bs[i] = bs[i-1] + dots[i-1].to_spring; } // dump(bs[N]); // dump(as[N]); // dump((long double)(as[si+1] - as[si])); // dump((long double)(bs[si+1] - bs[si])); auto f = [&](long double c){ int k = 0; for(k=0;k<N;k++){ if(dots[k].to_goal - dots[k].to_spring > c + 1e-9){ break; } } if(si < k){ return (long double)(as[si+1]-as[si]); }else{ return (bs[si+1] - bs[si]) + calc_e(dots,as,bs,k); } }; int ls = as[1] - bs[1]; int rs = as[N] - as[N-1] - (bs[N] - bs[N-1]); auto r = ternary_search_concave(f,ls,rs); // for(int i=0;i<N;i++){ // double d = as[i+1] - as[i] - (bs[i+1] - bs[i]); // cerr << d << " -> " << f(d) << endl; // } cout << fixed << setprecision(12); cout << f(r) << endl; return 0; */ }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<cstdio> #include<cstring> #include<vector> #include<queue> #include<algorithm> #include<cmath> #include<climits> #include<string> #include<set> #include<map> #include<iostream> using namespace std; #define rep(i,n) for(int i=0;i<((int)(n));i++) #define reg(i,a,b) for(int i=((int)(a));i<=((int)(b));i++) #define irep(i,n) for(int i=((int)(n))-1;i>=0;i--) #define ireg(i,a,b) for(int i=((int)(b));i>=((int)(a));i--) typedef long long int lli; typedef pair<int,int> mp; #define fir first #define sec second #define IINF INT_MAX #define LINF LLONG_MAX #define eprintf(...) fprintf(stderr,__VA_ARGS__) #define pque(type) priority_queue<type,vector<type>,greater<type> > #define memst(a,b) memset(a,b,sizeof(a)) typedef long double lld; typedef pair<lld,mp> lmp; int w,h; char dat[505][505]; lld ds[505][505]; int sy,sx,gy,gx; int dd[5]={1,0,-1,0,1}; void calcd(lld m){ pque(lmp) que; que.push(lmp(0,mp(gy,gx))); rep(y,h)rep(x,w){ if(dat[y][x]=='*'){ ds[y][x]=m; rep(i,4){ int ty = y + dd[i], tx = x + dd[i+1]; if(dat[ty][tx]!='.')continue; que.push(lmp(m+1,mp(ty,tx))); } } else ds[y][x]=-1; } while(!que.empty()){ lmp pa = que.top(); que.pop(); lld d = pa.fir; int y = pa.sec.fir, x = pa.sec.sec; if(ds[y][x]>=0)continue; ds[y][x]=d; rep(i,4){ int ty = y + dd[i], tx = x + dd[i+1]; if(dat[ty][tx]!='.')continue; if(ds[ty][tx]>=0)continue; que.push(lmp(d+1,mp(ty,tx))); } } } int main(void){ scanf("%d%d",&w,&h); rep(y,h)scanf("%s",dat[y]); rep(y,h)rep(x,w){ if(dat[y][x]=='s'){ sy=y; sx=x; dat[y][x]='.'; } if(dat[y][x]=='g'){ gy=y; gx=x; } } lld l=1e-20,r=1e20; while((r-l)/l>1e-15){ lld m = (l+r)/2.0; //printf("%Lf %Lf\n",l,r); calcd(m); int p = 0; lld s = 0; rep(y,h)rep(x,w){ if(dat[y][x]=='.'){ p++; s+=ds[y][x]; } } s /= p; if(s>=m)l = m; else r = m; } calcd(l); printf("%.15Lf\n",ds[sy][sx]); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <string> #include <vector> #include<iostream> #include<cstdio> #include<cstdlib> #include<stack> #include<queue> #include<cmath> #include<algorithm> #include<functional> #include<list> #include<deque> #include<bitset> #include<set> #include<map> #include<cstring> #include<sstream> #include<complex> #include<iomanip> #include<numeric> #define X first #define Y second #define pb push_back #define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X)) #define rrep(X,Y) for (int (X) = (Y-1);(X) >=0;--(X)) #define repe(X,Y) for ((X) = 0;(X) < (Y);++(X)) #define peat(X,Y) for (;(X) < (Y);++(X)) #define all(X) (X).begin(),(X).end() #define rall(X) (X).rbegin(),(X).rend() //#define int long long using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,pii> piii; typedef pair<ll,ll> pll; template<class T> ostream& operator<<(ostream &os, const vector<T> &t) { os<<"{"; rep(i,t.size()) {os<<t[i]<<",";} os<<"}"<<endl; return os;} template<class S, class T> ostream& operator<<(ostream &os, const pair<S,T> &t) { return os<<"("<<t.first<<","<<t.second<<")";} ll d[512][512],INF=5e15,d2[512][512], dx[]={1,0,-1,0},dy[]={0,1,0,-1},dd[512][512]; int main(){ ios_base::sync_with_stdio(false); cout<<fixed<<setprecision(10); // cout<<sizeof(ll)<<endl; int i,j,k,n,m,sx,sy,gx,gy; cin>>m>>n; vector<string> mp(n); rep(i,n) cin>>mp[i]; fill(d[0],d[511]+512,INF); fill(d2[0],d2[511]+512,INF); queue<pii> que,que2; rep(i,n)rep(j,m){ if(mp[i][j]=='s'){ sx=j; sy=i; }else if(mp[i][j]=='g'){ gx=j; gy=i; que.push(pii(j,i)); d[i][j]=0; }else if(mp[i][j]=='*'){ que2.push(pii(j,i)); d2[i][j]=0; } } while(!que.empty()){ pii p=que.front();que.pop(); rep(i,4){ int x=p.X+dx[i],y=p.Y+dy[i]; if(mp[y][x]!='#' && mp[y][x]!='*' && d[y][x]>d[p.Y][p.X]+1){ d[y][x]=d[p.Y][p.X]+1; que.push(pii(x,y)); } } } while(!que2.empty()){ pii p=que2.front();que2.pop(); rep(i,4){ int x=p.X+dx[i],y=p.Y+dy[i]; if(mp[y][x]!='#' && d2[y][x]>d2[p.Y][p.X]+1){ d2[y][x]=d2[p.Y][p.X]+1; que2.push(pii(x,y)); } } } // rep(i,n){rep(j,m)cout<<d[i][j]<<",";cout<<endl;}cout<<endl; // rep(i,n){rep(j,m)cout<<d2[i][j]<<",";cout<<endl;} priority_queue<piii> q; ll a=0,b=0,nn=0; rep(i,n)rep(j,m){ if(mp[i][j]!='#' && mp[i][j]!='*' && mp[i][j]!='g'){ q.push(piii(d[i][j]-d2[i][j],pii(j,i))); b+=d[i][j]; nn++; } } // cout<<b<<","<<nn<<":"<<1.*b/(nn-a)<<endl; //cout<<d[sy][sx]*(1-dd[sy][sx])+(d2[sy][sx]+1.*b/(nn-a))*dd[sy][sx]<<endl; while(!q.empty()){ piii tmp=q.top();q.pop(); if(nn-a==1)break; if(tmp.X<1.*(b)/(nn-a)) break; //cout<<tmp.Y<<tmp.X+d2[tmp.Y.Y][tmp.Y.X]<<"->"; pii p=tmp.Y; b-=tmp.X; ++a; dd[p.Y][p.X]=1; // cout<<1.*b/(nn-1)+d2[tmp.Y.Y][tmp.Y.X]<<endl; //cout<<a<<","<<b<<endl; } cout<<d[sy][sx]*(1-dd[sy][sx])+(d2[sy][sx]+1.*b/(nn-a))*dd[sy][sx]<<endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <iomanip> #include <vector> #include <queue> using namespace std; using ll = long long; using ld = long double; using P = pair<int, int>; constexpr int dir[5] = {0, 1, 0, -1, 0}; int main() { ll W, H; cin >> W >> H; vector<vector<char>> field(H, vector<char>(W)); P s, g; vector<P> spring; ll floor = 0; for (ll i = 0; i < H; i++) { for (ll j = 0; j < W; j++) { cin >> field[i][j]; if (field[i][j] == 's') { s = make_pair(i, j); field[i][j] = '.'; floor++; } else if (field[i][j] == 'g') { g = make_pair(i, j); } else if (field[i][j] == '*') { spring.push_back(make_pair(i, j)); } else if (field[i][j] == '.') { floor++; } } } constexpr ll INF = 1LL << 60; vector<vector<ll>> goal_dist(H, vector<ll>(W, INF)); vector<vector<ll>> spring_dist(H, vector<ll>(W, INF)); vector<vector<bool>> used(H, vector<bool>(W, false)); queue<pair<P, ll>> q; q.push(make_pair(g, 0)); while (not q.empty()) { const auto& s = q.front(); const ll y = s.first.first; const ll x = s.first.second; const ll dist = s.second; q.pop(); used[y][x] = true; goal_dist[y][x] = dist; for (ll d = 0; d < 4; d++) { const ll newx = x + dir[d]; const ll newy = y + dir[d + 1]; if (newx >= 0 and newx < W and newy >= 0 and newy < H and (not used[newy][newx]) and (field[newy][newx] == '.')) { used[newy][newx] = true; q.push(make_pair(make_pair(newy, newx), dist + 1)); } } } fill(used.begin(), used.end(), vector<bool>(W, false)); for (const P& sp : spring) { q.push(make_pair(sp, 0)); } while (not q.empty()) { const auto& s = q.front(); const ll y = s.first.first; const ll x = s.first.second; const ll dist = s.second; q.pop(); used[y][x] = true; spring_dist[y][x] = dist; for (ll d = 0; d < 4; d++) { const ll newx = x + dir[d]; const ll newy = y + dir[d + 1]; if (newx >= 0 and newx < W and newy >= 0 and newy < H and (not used[newy][newx]) and (field[newy][newx] == '.')) { used[newy][newx] = true; q.push(make_pair(make_pair(newy, newx), dist + 1)); } } } ld inf = 0; ld sup = 10000000000; constexpr ll REP = 1000; for (ll i = 0; i < REP; i++) { const ld mid = (inf + sup) / 2; ld sum = 0; for (ll y = 0; y < H; y++) { for (ll x = 0; x < W; x++) { if (field[y][x] == '.') { sum += min(spring_dist[y][x] + mid, (ld)goal_dist[y][x]); } } } const ld actual = sum / floor; if (actual < mid) { sup = mid; } else { inf = mid; } } const ll sy = s.first; const ll sx = s.second; cout << fixed << setprecision(15) << min(spring_dist[sy][sx] + inf, (ld)goal_dist[sy][sx]) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <cstdlib> #include <iostream> #include <queue> #include <vector> using namespace std; constexpr long long INF = (1ll << 50); void bfs(int sx, int sy, const vector<string> &field, vector<vector<long long>> &dist) { typedef pair<int, int> point; constexpr int dx[] = {1, 0, -1, 0}; constexpr int dy[] = {0, 1, 0, -1}; queue<point> que; que.push({sx, sy}); dist[sy][sx] = 0; while(!que.empty()) { const int x = que.front().first; const int y = que.front().second; que.pop(); for(int d = 0; d < 4; ++d) { const int nx = x + dx[d]; const int ny = y + dy[d]; if(field[ny][nx] == '.' && dist[ny][nx] > dist[y][x] + 1) { dist[ny][nx] = dist[y][x] + 1; que.push({nx, ny}); } } } } double calc(double E, const vector<pair<long long, long long>> &values) { double sum = 0.0; for(const auto &e : values) { sum += min<double>(e.first, e.second + E); } return sum / values.size(); } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(12); int w, h; cin >> w >> h; vector<string> field(h); for(auto &e : field) cin >> e; int sx, sy; for(int i = 0; i < h; ++i) { for(int j = 0; j < w; ++j) { if(field[i][j] == 's') { sx = j; sy = i; field[i][j] = '.'; goto bfs_phase; } } } bfs_phase:; vector<vector<long long>> from_goal(h, vector<long long>(w, INF)); vector<vector<long long>> from_spring(h, vector<long long>(w, INF)); for(int i = 0; i < h; ++i) { for(int j = 0; j < w; ++j) { if(field[i][j] == 'g') { bfs(j, i, field, from_goal); } else if(field[i][j] == '*') { bfs(j, i, field, from_spring); } } } vector<pair<long long, long long>> values; values.reserve(h * w); for(int i = 0; i < h; ++i) { for(int j = 0; j < w; ++j) { if(field[i][j] == '.') { values.emplace_back(from_goal[i][j], from_spring[i][j]); } } } double L = 0.0, R = INF; for(int i = 0; i < 100; ++i) { const double M = (L + R) / 2.0; if(calc(M, values) < M) { R = M; } else { L = M; } } cout << min<double>(from_goal[sy][sx], from_spring[sy][sx] + L) << endl; return EXIT_SUCCESS; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <iomanip> #include <vector> #include <string> #include <queue> using namespace std; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; int H, W; vector<string> fi; using pint = pair<int,int>; void bfs(queue<pint> &que, vector<vector<int> > &dist) { while (!que.empty()) { auto p = que.front(); que.pop(); for (int dir = 0; dir < 4; ++dir) { int nx = p.first + dx[dir], ny = p.second + dy[dir]; if (nx < 0 || nx >= H || ny < 0 || ny >= W) continue; if (fi[nx][ny] != '.' && fi[nx][ny] != 's') continue; if (dist[nx][ny] == -1) { dist[nx][ny] = dist[p.first][p.second] + 1; que.push(pint(nx, ny)); } } } } int main() { cin >> W >> H; fi.resize(H); for (int i = 0; i < H; ++i) cin >> fi[i]; pint s, g; vector<pint> ss; for (int i = 0; i < H; ++i) for (int j = 0; j < W; ++j) { if (fi[i][j] == 'g') g = pint(i, j); else if (fi[i][j] == 's') s = pint(i, j); else if (fi[i][j] == '*') ss.push_back(pint(i, j)); } vector<vector<int> > dpg(H, vector<int>(W, -1)), dps(H, vector<int>(W, -1)); queue<pint> queg; queg.push(g), dpg[g.first][g.second] = 0; bfs(queg, dpg); queue<pint> ques; for (auto p : ss) ques.push(p), dps[p.first][p.second] = 0; bfs(ques, dps); double low = 0, high = 1LL<<60; for (int _ = 0; _ < 100; ++_) { double t = (low + high) / 2; //cout << "----------------" << endl; cout << t << endl; double sum = 0; int N = 0; for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (fi[i][j] != '.' && fi[i][j] != 's') continue; ++N; double tmp = 1LL<<60; if (dps[i][j] != -1 && tmp > dps[i][j] + t) tmp = dps[i][j] + t; if (dpg[i][j] != -1 && tmp > dpg[i][j]) tmp = dpg[i][j]; sum += tmp; } } if (t * N >= sum) high = t; else low = t; } double res = 1LL<<60; if (dps[s.first][s.second] != -1 && res > dps[s.first][s.second] + high) res = dps[s.first][s.second] + high; if (dpg[s.first][s.second] != -1 && res > dpg[s.first][s.second]) res = dpg[s.first][s.second]; cout << fixed << setprecision(12) << res << endl; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> using namespace std; using Int = long long; using Double = long double; signed main(){ Int h,w; cin>>w>>h; vector<string> s(h); for(Int i=0;i<h;i++) cin>>s[i]; vector<vector<Int> > dg(h,vector<Int>(w,-1)),ds=dg; using T = pair<Int,int>; queue<T> qg,qs; for(Int i=0;i<h;i++){ for(Int j=0;j<w;j++){ if(s[i][j]=='g'){ qg.push(T(i,j)); dg[i][j]=0; } if(s[i][j]=='*'){ qs.push(T(i,j)); ds[i][j]=0; } } } Int dy[]={0,0,1,-1}; Int dx[]={1,-1,0,0}; auto bfs=[&](queue<T> &q,vector<vector<Int> > &d){ while(!q.empty()){ T t=q.front();q.pop(); Int y=t.first,x=t.second; for(Int k=0;k<4;k++){ Int ny=y+dy[k],nx=x+dx[k]; if(s[ny][nx]=='#'||s[ny][nx]=='*') continue; if(~d[ny][nx]&&d[ny][nx]<=d[y][x]+1) continue; d[ny][nx]=d[y][x]+1; q.push(T(ny,nx)); } } if(0){ cout<<endl; for(Int i=0;i<h;i++){ for(Int j=0;j<w;j++){ if(d[i][j]<0) cout<<"x"; else cout<<hex<<d[i][j]; } cout<<endl; } } }; bfs(qg,dg); bfs(qs,ds); auto get=[&](Int i,Int j,Double p){ if(~dg[i][j]&&~ds[i][j]) return min((Double)dg[i][j],ds[i][j]+p); if(~ds[i][j]) return ds[i][j]+p; if(~dg[i][j]) return (Double)dg[i][j]; return Double(0); }; auto calc=[&](Double p){ Double q=0,c=0; for(Int i=0;i<h;i++){ for(Int j=0;j<w;j++){ if(s[i][j]=='#'||s[i][j]=='g'||s[i][j]=='*') continue; c+=1.0; q+=get(i,j,p); } } q/=c; //printf("%.12Lf %.12Lf\n",p, p-q); return p-q; }; Double l=0,r=1e15; for(int k=0;k<1000;k++){ //while(abs(calc(l))>1e-10){ Double m=(l+r)/2; if(calc(m)<=Double(0)) l=m; else r=m; } //printf("%.12f\n",calc(l)); for(Int i=0;i<h;i++) for(Int j=0;j<w;j++) if(s[i][j]=='s') printf("%.12Lf\n",get(i,j,l)); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <set> #include <cstdio> #include <queue> #include <algorithm> #define REP(i,n) for(int i=0; i<(int)(n); i++) #define IN(x,s,g) ((x) >= (s) && (x) < (g)) #define ISIN(x,y,w,h) (IN((x),0,(w)) && IN((y),0,(h))) using namespace std; int w, h; char g[512][512]; int sx, sy; int gx, gy; int all; int dg[512][512]; int ds[512][512]; const int _dx[] = {0,1,0,-1}; const int _dy[] = {-1,0,1,0}; int main(){ scanf("%d%d", &w, &h); REP(i,h) scanf("%s", g[i]); queue<pair<int, int> > gq; queue<pair<int, int> > sq; REP(i,h) REP(j,w){ dg[i][j] = ds[i][j] = -1; if(g[i][j] == '.' || g[i][j] == 's') all++; if(g[i][j] == 's'){ sx = j; sy = i; g[i][j] = '.'; }else if(g[i][j] == 'g'){ gx = j; gy = i; gq.push(make_pair(i, j)); dg[i][j] = 0; }else if(g[i][j] == '*'){ sq.push(make_pair(i, j)); ds[i][j] = 0; } } // bfs1 while(gq.size()){ int x = gq.front().second; int y = gq.front().first; gq.pop(); REP(i,4){ int xx = x + _dx[i]; int yy = y + _dy[i]; if(ISIN(xx, yy, w, h) && dg[yy][xx] == -1 && g[yy][xx] == '.'){ dg[yy][xx] = dg[y][x] + 1; gq.push(make_pair(yy, xx)); } } } // REP(i,h){ REP(j,w) printf("%2d ", dg[i][j]); puts(""); } // bfs2 while(sq.size()){ int x = sq.front().second; int y = sq.front().first; sq.pop(); REP(i,4){ int xx = x + _dx[i]; int yy = y + _dy[i]; if(ISIN(xx, yy, w, h) && ds[yy][xx] == -1 && g[yy][xx] == '.'){ ds[yy][xx] = ds[y][x] + 1; sq.push(make_pair(yy, xx)); } } } // REP(i,h) { REP(j,w) printf("%2d ", ds[i][j]); puts(""); } double ans = 1e10; int cnt = 0; long long chokusetsu = 0; long long tospring = 0; if(dg[sy][sx] != -1) ans = dg[sy][sx]; // spring = p * chokusetsu + (1 - p) * (tospring + spring) // p * spring = p * chokusetsu + (1 - p) * tospring // spring = chokusetsu + (1 - p) / p * tospring vector<pair<int, pair<int, int> > > pos; REP(i,h) REP(j,w) if(g[i][j] == '.'){ int d = dg[i][j]; if(d == -1){ tospring += ds[i][j]; }else{ chokusetsu += d; cnt++; int dd = ds[i][j]; if(dd != -1 && dd < d){ pos.push_back(make_pair(-(d - dd), make_pair(i, j))); } } } sort(pos.begin(), pos.end()); size_t idx = 0; while(idx != pos.size() && cnt != 0){ double p = (double)cnt / all; // printf("cnt: %d, all: %d, ans: %.3f\n", cnt, all, ans); if(cnt != all && ds[sy][sx] != -1) ans = min(ans, ds[sy][sx] + (double)chokusetsu / cnt + (1 - p) / p * ((double)tospring / (all - cnt))); int d = pos[idx].first; while(idx != pos.size() && pos[idx].first == d){ int x = pos[idx].second.second; int y = pos[idx].second.first; if(ds[y][x] != -1){ cnt--; chokusetsu -= dg[y][x]; tospring += ds[y][x]; } idx++; } } double p = (double)cnt / all; if(cnt != 0 && cnt != all && ds[sy][sx] != -1) ans = min(ans, ds[sy][sx] + (double)chokusetsu / cnt + (1 - p) / p * ((double)tospring / (all - cnt))); printf("%.10f\n", ans); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; #define inf (int)(1e18) #define int long long #define double long double signed main(){ int H, W, i, j, v; scanf("%lld%lld", &W, &H); vector<string> c(H); int sx, sy, floor = 0; queue<pair<pair<int, int>, int>> q1, q2; for(i = 0; i < H; i++){ cin >> c[i]; for(j = 0; j < W; j++){ if(c[i][j] == 's'){ sx = i; sy = j; c[i][j] = '.'; } if(c[i][j] == 'g'){ q1.push(pair<pair<int, int>, int>(pair<int, int>(i, j), 0)); } if(c[i][j] == '*'){ q2.push(pair<pair<int, int>, int>(pair<int, int>(i, j), 0)); } if(c[i][j] == '.'){ floor++; } } } int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int d; vector<vector<int>> A1(H, vector<int>(W, inf)); while(q1.size() > 0){ i = q1.front().first.first; j = q1.front().first.second; v = q1.front().second; q1.pop(); if(c[i][j] == '#' || c[i][j] == '*' || A1[i][j] <= v){ continue; } A1[i][j] = v; for(d = 0; d < 4; d++){ q1.push(pair<pair<int, int>, int>(pair<int, int>(i + dx[d], j + dy[d]), v + 1)); } } vector<vector<int>> A2(H, vector<int>(W, inf)); while(q2.size() > 0){ i = q2.front().first.first; j = q2.front().first.second; v = q2.front().second; q2.pop(); if(c[i][j] == '#' || c[i][j] == 'g' || A2[i][j] <= v){ continue; } A2[i][j] = v; for(d = 0; d < 4; d++){ q2.push(pair<pair<int, int>, int>(pair<int, int>(i + dx[d], j + dy[d]), v + 1)); } } /* printf("floor = %d\n", floor); printf("A1\n"); for(i = 0; i < H; i++){ for(j = 0; j < W; j++){ printf("%2d ", A1[i][j]); } printf("\n"); } printf("A2\n"); for(i = 0; i < H; i++){ for(j = 0; j < W; j++){ printf("%2d ", A2[i][j]); } printf("\n"); } */ double l = 0, h, r = 1e12; for(int k = 0; k < 200; k++){ // printf("(l, r) = (%lf, %lf)\n", l, r); h = (l + r) / 2; double hf = 0; for(i = 0; i < H; i++){ for(j = 0; j < W; j++){ if(c[i][j] == '.'){ hf += min((double)A1[i][j], A2[i][j] + h); } } } // printf("(h, hf) = (%lf, %lf)\n", h, hf); if(h * floor < hf){ l = h; } else{ r = h; } } printf("%.20Lf\n", min((double)A1[sx][sy], A2[sx][sy] + r)); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> using namespace std; typedef long long ll; int H,W; int dy[]={-1,0,1,0}; int dx[]={0,1,0,-1}; char t[500][500]; ll A[500][500],B[500][500]; ll INF=(1LL<<50); void bfs(char ch,ll d[500][500]){ fill(d[0],d[500], INF ); queue<int> qy,qx; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(ch==t[i][j]){ d[i][j]=0; qy.push(i); qx.push(j); } } } while(!qy.empty()){ int y=qy.front();qy.pop(); int x=qx.front();qx.pop(); for(int dir=0;dir<4;dir++){ int ny=y+dy[dir]; int nx=x+dx[dir]; if(t[ny][nx]=='#')continue; if(t[ny][nx]=='*')continue; if(d[ny][nx]>d[y][x]+1){ d[ny][nx]=d[y][x]+1; qy.push(ny); qx.push(nx); } } } } int main(){ cin>>W>>H; for(int i=0;i<H;i++) for(int j=0;j<W;j++) cin>>t[i][j]; bfs('*',A); bfs('g',B); vector<ll> v; ll sum=0,cnt=0,K=0; double base=1e100; double ans=1e100; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(t[i][j]=='#')continue; if(t[i][j]=='*')continue; if(t[i][j]=='g')continue; cnt++; if(t[i][j]=='s'){ if(A[i][j]==INF)base=1e100; else base=A[i][j]; if(B[i][j]!=INF)ans=B[i][j]; } if(A[i][j]==INF){ sum+=B[i][j]; }else if(B[i][j]==INF){ sum+=A[i][j]; K++; }else{ sum+=B[i][j]; v.push_back(A[i][j]-B[i][j]); } } } sort(v.begin(),v.end()); for(int i=0;i<=(int)v.size();i++){ double rate=(double)K/(double)cnt; double X=(double)sum/(double)cnt; X/=(1.0-rate); ans=min(ans,(double)base+X); K++; if(i==(int)v.size())break; sum+=v[i]; } printf("%.12f\n",ans); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
// #ifdef DEBUG // #define _GLIBCXX_DEBUG // #endif #include <iostream> #include <iomanip> #include <vector> #include <valarray> #include <map> #include <set> #include <list> #include <queue> #include <stack> #include <bitset> #include <utility> #include <numeric> #include <algorithm> #include <functional> #include <complex> #include <string> #include <sstream> #include <cstdio> #include <cstdlib> #include <cctype> #include <cstring> // these require C++11 #include <unordered_set> #include <unordered_map> #include <random> #include <thread> #include <chrono> #include <tuple> using namespace std; #define int long long #define all(c) c.begin(), c.end() #define repeat(i, n) for (int i = 0; i < static_cast<int>(n); i++) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define dump(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define dump(x) #endif template<typename A,typename B> ostream &operator<<(ostream&os,const pair<A,B>& p){ os << "(" << p.first << "," << p.second << ")"; return os; } typedef complex<double> point; // template<typename T,std::size_t N> // struct _v_traits {using type = std::vector<typename _v_traits<T,N-1>::type>;}; // template<typename T> // struct _v_traits<T,1> {using type = std::vector<T>;}; // template<typename T,std::size_t N=1> // using vec = typename _v_traits<T,N>::type; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } const int INF = 1000000000000000ll; struct Info { int to_goal; int to_spring; bool is_start; }; ostream &operator<<(ostream &os, const Info &i) { return os << "(" << i.to_goal << "," << i.to_spring << ")"; } const char wall = '#'; const char spring = '*'; const char dot = '.'; const char start = 's'; const char goal = 'g'; const vector<int> dx = {-1,0,1,0}; const vector<int> dy = {0, 1,0,-1}; // 凸関数の極大な点をもとめる template<typename F,typename T> T ternary_search(F f,T left,T right,int try_cnt = 100){ for(int i=0;i<try_cnt;i++){ T l = (2*left + right) / 3; T r = (left + 2*right) / 3; if(f(l) < f(r)){ left = l; }else{ right = r; } } return (left+right)/2; } // 凹関数の極小な・を求める template<typename F,typename T> T ternary_search_concave(F f,T left,T right,int try_cnt=1000){ return ternary_search([f](T x){return -f(x);},left,right); } // [0 ~ k) long double calc_e(const vector<Info>& v, const vector<int>& as, const vector<int>& bs, const int k){ const int N = v.size(); long double l = as[k]; long double r = bs[N] - bs[k]; return (l+r) / k; } signed main() { ios::sync_with_stdio(false); cin.tie(0); int W,H; cin >> W >> H; vector<string> field(H); for(string& s : field){ cin >> s; } vector<vector<Info> > info(H,vector<Info>(W,Info{INF,INF,false})); for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(field[i][j] == start) info[i][j].is_start = true; } } for(int to_finding_spring=0;to_finding_spring<2;to_finding_spring++){ // value,y,x queue<tuple<int,int,int> > queue; set<tuple<int,int> > already; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if((to_finding_spring and field[i][j] == spring) or (!to_finding_spring and field[i][j] == goal)){ queue.emplace(0,i,j); } } } while(not queue.empty()){ auto t = queue.front(); queue.pop(); int v = get<0>(t); int y = get<1>(t); int x = get<2>(t); if(already.find(make_tuple(y,x)) != already.end()){ continue; } if(to_finding_spring && (field[y][x] == wall or field[y][x] == goal)){ continue; } if(not to_finding_spring && (field[y][x] == wall or field[y][x] == spring)){ continue; } already.insert(make_tuple(y,x)); if(to_finding_spring){ info[y][x].to_spring = v; }else{ info[y][x].to_goal = v; } for(int i=0;i<4;i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(0 <= nx and nx < W and 0 <= ny and ny < H and already.find(make_tuple(ny,nx)) == already.end()){ queue.emplace(v+1,ny,nx); } } } } vector<Info> dots; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(field[i][j] == dot || field[i][j] == start){ dots.push_back(info[i][j]); } } } // 階段が近い → 遠い sort(dots.begin(),dots.end(),[](const Info& left,const Info& right){ int l = left.to_goal - left.to_spring; int r = right.to_goal - right.to_spring; return l < r; }); int si = find_if(dots.begin(),dots.end(),[](const Info& i){return i.is_start;}) - dots.begin(); int N = dots.size(); vector<int> as(N+1); vector<int> bs(N+1); for(int i=1;i<N+1;i++){ as[i] = as[i-1] + dots[i-1].to_goal; bs[i] = bs[i-1] + dots[i-1].to_spring; } map<tuple<int,int>,long double> memo; auto f = [&](long double c){ int k = 0; for(k=0;k<N;k++){ if(dots[k].to_goal - dots[k].to_spring > c + 1e-9){ break; } } if(si < k){ return (long double)(as[si+1]-as[si]); }else{ return (bs[si+1] - bs[si]) + calc_e(dots,as,bs,k); } }; long double ls = 1e-15; long double rs = 1e15; auto r = ternary_search_concave(f,ls,rs); cout << fixed << setprecision(12); cout << f(r) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; #define rep(i,x,y) for(int i=(x);i<(y);++i) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define _GLIBCXX_DEBUG #define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define print(x) #endif const int inf=1e9; const int64_t inf64=1e18; const double eps=1e-9; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){ os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } void solve(){ int w,h; cin >> w >> h; vector<string> c(h); int sy,sx,gy,gx; rep(i,0,h){ cin >> c[i]; rep(j,0,w){ if(c[i][j]=='s'){ sy=i; sx=j; } if(c[i][j]=='g'){ gy=i; gx=j; } } } int dy[]={0,1,0,-1},dx[]={1,0,-1,0}; vector<vector<int64_t>> a(h,vector<int64_t>(w,inf64)),b(h,vector<int64_t>(w,inf64)); auto ok=[&](int y,int x){ return 0<=y and y<h and 0<=x and x<w and (c[y][x]=='.' or c[y][x]=='s'); }; auto bfs=[&](int y0,int x0,int c){ queue<tuple<int,int,int64_t>> que; que.push(make_tuple(y0,x0,0)); while(!que.empty()){ tuple<int,int,int> t=que.front(); que.pop(); int y=get<0>(t),x=get<1>(t); int64_t d=get<2>(t); if(c==0){ if(a[y][x]<=d) continue; a[y][x]=d; } if(c==1){ if(b[y][x]<=d) continue; b[y][x]=d; } rep(i,0,4){ int ny=y+dy[i],nx=x+dx[i]; if(!ok(ny,nx)) continue; que.push(make_tuple(ny,nx,d+1)); } } }; rep(i,0,h){ rep(j,0,w){ if(c[i][j]=='*') bfs(i,j,0); if(c[i][j]=='g') bfs(i,j,1); } } auto g=[&](long double e){ long double sum=0; int count=0; rep(y,0,h){ rep(x,0,w){ if(c[y][x]=='#' or c[y][x]=='*' or c[y][x]=='g') continue; sum+=min(a[y][x]+e,(long double)b[y][x]); ++count; } } return sum/count; }; long double lb=0,ub=inf64; rep(i,0,128){ long double mid=(lb+ub)/2; if(mid<g(mid)) lb=mid; else ub=mid; } cout << min(a[sy][sx]+lb,(long double)b[sy][sx]) << endl; } int main(){ std::cin.tie(0); std::ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(12); solve(); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; typedef long double Double; const Double INF = 1e20; const double PI = acos(-1); const double EPS = 1e-8; char ba[500][500]; Double disg[500][500]; Double disb[500][500]; bool visited[500][500]; int dx[] = {-1,0,1,0}; int dy[] = {0,1,0,-1}; int h,w; void bfs(Double hoge[500][500], queue<pii> &Q, bool vis[500][500]) { while(!Q.empty()) { pii p = Q.front(); Q.pop(); int y = p.first; int x = p.second; REP(k, 4) { int yy = y+dy[k]; int xx = x+dx[k]; if (yy<0||yy>=h||xx<0||xx>=w) continue; if (ba[yy][xx] != '.') continue; if (vis[yy][xx]) continue; vis[yy][xx] = 1; hoge[yy][xx] = hoge[y][x] + 1; Q.push(pii(yy,xx)); } } } // C‚ð–ž‚½‚·‚à‚Ì‚ªub‘¤‚É‚ ‚èAC‚ð–ž‚½‚·Å¬’l‚ð‹‚ß‚é‚Æ‚«B template<class T> T lower_search(T lb, T ub, bool (*C)(T)) { REP(i, 200) { T mid = (lb+ub)/2; if (C(mid)) ub = mid; else lb = mid; } return ub; } int num = 0; bool C(Double E) { Double hoge = 0; REP(i, h) { REP(j, w) { if (ba[i][j] == '.') { if (disg[i][j] < disb[i][j] + E) { hoge += disg[i][j]; } else { hoge += disb[i][j] + E; } } } } hoge /= num; //cout << hoge << " "<< E << endl; return E >= hoge; } int main() { cin >> w >> h; int sx,sy,gx,gy; queue<pii> Q; memset(visited, 0, sizeof(visited)); REP(i,h)REP(j,w) disb[i][j] = disg[i][j] = INF; num = 0; REP(i, h) { REP(j, w) { cin >> ba[i][j]; if (ba[i][j] == 's') { sx = j; sy = i; ba[i][j] = '.'; num++; } else if (ba[i][j] == 'g') { gx = j; gy = i; } else if (ba[i][j] == '*') { Q.push(pii(i,j)); visited[i][j] = 1; disb[i][j] = 0; } else if (ba[i][j] == '.') { num++; } } } bfs(disb, Q, visited); memset(visited,0,sizeof(visited)); disg[gy][gx] = 0; visited[gy][gx] = 1; Q.push(pii(gy,gx)); bfs(disg, Q, visited); // REP(i, h) { // REP(j, w) { // if (disb[i][j] == INF) cout << "* "; // else cout << disb[i][j] << " "; // } // cout << endl; // } // REP(i, h) { // REP(j, w) { // if (disg[i][j] >= INF)cout << "* "; // else cout << disg[i][j] << " "; // } // cout << endl; // } Double E = lower_search<Double>(0, 1e20, C); //cout << E << endl; Double ans = min((Double)disg[sy][sx],disb[sy][sx]+E); printf("%.12Lf\n", ans); }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <cstdio> #include <queue> #include <cmath> #include <cstring> #include <algorithm> #define INF 1e18 using namespace std; typedef pair<int,int> P; typedef pair<int,P> PP; int dx[4]={0,-1,0,1}; int dy[4]={1,0,-1,0}; int fie[510][510]; int dist[2][510][510]; int w,h; vector<PP> vec; int sx,sy,gx,gy; typedef long long ll; void bfs(int y=-1,int x=-1){ queue<P> que; int type=0; if(y==-1)type=1; memset(dist[type],-1,sizeof(dist[type])); if(type==0){ dist[type][y][x]=0; que.push(P(y,x)); }else{ for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(fie[i][j]==1){ dist[type][i][j]=0; que.push(P(i,j)); } } } } while(que.size()){ P p=que.front(); que.pop(); for(int i=0;i<4;i++){ int nx=p.second+dx[i],ny=p.first+dy[i]; if(abs(fie[ny][nx])!=1 && dist[type][ny][nx]==-1){ dist[type][ny][nx]=dist[type][p.first][p.second]+1; que.push(P(ny,nx)); } } } } ll cnt=0; ll all=0; ll okave=0; ll ngave=0; long double calc(int v){ if((dist[0][sy][sx]!=-1 && dist[0][sy][sx]<=dist[1][sy][sx]+v) || dist[1][sy][sx]==-1)return dist[0][sy][sx]; else{ if(cnt==0)return INF; long double va=(long double)okave/all; va*=(double)1.0*all/cnt; long double vb=(long double)ngave/((long double)(all-cnt)); vb*=(long double)1.0*all/cnt; vb-=(long double)ngave/((long double)(all-cnt)); return (long double)va+vb+dist[1][sy][sx]; } } int main(void){ scanf("%d%d%*c",&w,&h); memset(fie,0,sizeof(fie)); for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ char c; scanf("%c",&c); if(c=='#')fie[i][j]=-1; if(c=='s')sy=i,sx=j; if(c=='g')gy=i,gx=j; if(c=='*')fie[i][j]=1; } scanf("%*c"); } bfs(gy,gx); bfs(); if(dist[1][sy][sx]==-1 || (dist[0][sy][sx]<=dist[1][sy][sx] && dist[0][sy][sx]!=-1)){ printf("%.10f\n",(double)dist[0][sy][sx]); return 0; } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(fie[i][j]==0 && (i!=gy || j!=gx)){ all++; if(dist[0][i][j]!=-1 && dist[1][i][j]!=-1)vec.push_back(PP(dist[0][i][j]-dist[1][i][j],P(i,j))); else if(dist[0][i][j]==-1)ngave+=dist[1][i][j]; else{ okave+=dist[0][i][j]; cnt++; } } } } sort(vec.begin(),vec.end()); long double res=INF; for(int i=0;i<vec.size();i++){ ngave+=dist[1][vec[i].second.first][vec[i].second.second]; } for(int i=0;i<=vec.size();i++){ if(i==vec.size())res=min(res,calc(514514)); else if(all!=cnt || cnt!=0)res=min(res,calc(vec[i].first)); if(i!=vec.size()){ ngave-=dist[1][vec[i].second.first][vec[i].second.second]; cnt++; okave+=dist[0][vec[i].second.first][vec[i].second.second]; } } printf("%.10f\n",(double)res); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-10) #define equals(a,b) (fabs((a)-(b))<EPS) using namespace std; typedef long double ld; const int MAX = 501,IINF = INT_MAX; const ld LDINF = 1e100; int H,W,sx,sy,gx,gy; ld mincost[MAX][MAX][2]; // mincost[][][0] => from start, [1] = > from star char c[MAX][MAX]; bool ban[MAX][MAX]; vector<int> star,plane; int dx[] = {0,1,0,-1}; int dy[] = {1,0,-1,0}; inline bool isValid(int x,int y) { return 0 <= x && x < W && 0 <= y && y < H; } inline void bfs(vector<int> sp,vector<int> Forbidden,int type){ rep(i,H)rep(j,W) mincost[i][j][type] = LDINF, ban[i][j] = false; queue<int> que; rep(i,(int)sp.size()) que.push(sp[i]), mincost[sp[i]/W][sp[i]%W][type] = 0; rep(i,(int)Forbidden.size()) ban[Forbidden[i]/W][Forbidden[i]%W] = true; while(!que.empty()){ int cur = que.front(); que.pop(); rep(i,4){ int nx = cur % W + dx[i], ny = cur / W + dy[i]; if( c[ny][nx] == '#' ) continue; if( ban[ny][nx] ) continue; if( mincost[ny][nx][type] == LDINF ) { mincost[ny][nx][type] = mincost[cur/W][cur%W][type] + 1; que.push(nx+ny*W); } } } } bool check(ld E){ ld T = 0; rep(i,(int)plane.size()){ int x = plane[i] % W, y = plane[i] / W; T += min(mincost[y][x][0],mincost[y][x][1]+E); } ld len = plane.size(); return len * E > T; } int main(){ cin >> W >> H; rep(i,H)rep(j,W){ cin >> c[i][j]; if( c[i][j] == 's' ) sx = j, sy = i, c[i][j] = '.'; if( c[i][j] == 'g' ) gx = j, gy = i; if( c[i][j] == '*' ) star.push_back(j+i*W); if( c[i][j] == '.' ) plane.push_back(j+i*W); } vector<int> sp,forbidden; sp.push_back(gx+gy*W); forbidden = star; forbidden.push_back(gx+gy*W); bfs(sp,forbidden,0); sp = star; forbidden.push_back(gx+gy*W); //forbidden.clear(); bfs(sp,forbidden,1); ld L = 0, R = 1e10, M = 0; rep(i,70){ M = ( L + R ) * (ld)0.5; if( check(M) ) R = M; else L = M; } cout << setiosflags(ios::fixed) << setprecision(20) << min((ld)mincost[sy][sx][0],(ld)mincost[sy][sx][1]+L) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<iostream> #include<string> #include<vector> #include<queue> #include<string.h> #include<algorithm> using namespace std; class C{ public: int x,y; C(int x,int y):x(x),y(y){} }; const int dx[]={1,0,-1,0}; const int dy[]={0,1,0,-1}; int w,h; bool in(int x,int y){ if(x<0 || y<0 || x>=w || y>=h) return false; return true; } long long int dist_goal[500][500],dist_spring[500][500]; const long long INF=10000000000LL; int main() { /* double m=1000000000000.0; for(int i=0;i<1000;i++){ cout<<m<<endl; m/=2.0; }*/ cin>>w>>h; int gx,gy,sx,sy; vector<string> M(h); vector<C> spring; long long num_normal=0; for(int i=0;i<h;i++){ cin>>M[i]; for(int j=0;j<M[i].size();j++){ if(M[i][j]=='s'){sx=j;sy=i;num_normal++;} if(M[i][j]=='g'){gx=j;gy=i;} if(M[i][j]=='*'){spring.push_back(C(j,i));} if(M[i][j]=='.'){num_normal++;} } } for(int i=0;i<500;i++) for(int j=0;j<500;j++){ dist_goal[i][j]=INF; dist_spring[i][j]=INF; } bool visit[500][500]; memset(visit,false,sizeof(visit)); queue<pair<C,int> > que; que.push(make_pair(C(gx,gy),0)); while(!que.empty()){ C now=que.front().first; int cost=que.front().second; que.pop(); if(!in(now.x,now.y)) continue; if(M[now.y][now.x]=='#' || M[now.y][now.x]=='*') continue; if(visit[now.y][now.x]) continue; visit[now.y][now.x]=true; dist_goal[now.y][now.x]=cost; for(long long r=0;r<4;r++){ que.push(make_pair(C(now.x+dx[r],now.y+dy[r]),cost+1)); } } for(long long i=0;i<spring.size();i++) que.push(make_pair(C(spring[i].x,spring[i].y),0)); memset(visit,false,sizeof(visit)); while(!que.empty()){ C now=que.front().first; long long cost=que.front().second; que.pop(); if(!in(now.x,now.y)) continue; if(M[now.y][now.x]=='#') continue; if(visit[now.y][now.x]) continue; visit[now.y][now.x]=true; dist_spring[now.y][now.x]=cost; for(int r=0;r<4;r++){ que.push(make_pair(C(now.x+dx[r],now.y+dy[r]),cost+1)); } } const int NUM=1000; long double upper=1e20,lower=0.0; for(int t=0;t<NUM;t++){ long double sum=0.0; long double E=(upper+lower)/2.0; vector<long double> work; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ if(M[y][x]!='.' && M[y][x]!='s') continue; if(dist_goal[y][x]<INF) work.push_back(min((double)dist_goal[y][x],(double)dist_spring[y][x]+(double)E)); else work.push_back(dist_spring[y][x]+E); } } // sort(work.begin(),work.end()); for(int i=0;i<work.size();i++) sum+=work[i]; // cout<<sum/num_normal<<endl; if(sum/num_normal<E) upper=E-1e-10; else lower=E+1e-10; } // cout<<min((double)dist_goal[sy][sx],(upper+lower)/2.0+dist_spring[sy][sx])<<endl; printf("%.13lf\n",min((double)dist_goal[sy][sx],(double)(upper+lower)/2.0+dist_spring[sy][sx])); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; constexpr int INF = 1e9; constexpr int dx[4] = {0, 1, 0, -1}; constexpr int dy[4] = {1, 0, -1, 0}; int main() { int W, H; cin >> W >> H; vector<string> v(H); int s, g; int fcnt = 0; queue<int> que; vector<int> sd(H * W, INF); for(int i = 0; i < H; ++i) { cin >> v[i]; for(int j = 0; j < W; ++j) { if(v[i][j] == 's') { s = i * W + j; } else if(v[i][j] == 'g') { g = i * W + j; } else if(v[i][j] == '*') { que.push(i * W + j); sd[i * W + j] = 0; } fcnt += v[i][j] == '.' || v[i][j] == 's'; } } while(!que.empty()) { int y = que.front() / W; int x = que.front() % W; que.pop(); for(int i = 0; i < 4; ++i) { int ny = y + dy[i]; int nx = x + dx[i]; if(ny < 0 || H <= ny || nx < 0 || W <= nx || v[ny][nx] == '#' || v[ny][nx] == 'g' || sd[ny * W + nx] != INF) { continue; } sd[ny * W + nx] = sd[y * W + x] + 1; que.push(ny * W + nx); } } vector<int> gd(H * W, INF); que.push(g); gd[g] = 0; double total_gd = 0; while(!que.empty()) { int y = que.front() / W; int x = que.front() % W; que.pop(); for(int i = 0; i < 4; ++i) { int ny = y + dy[i]; int nx = x + dx[i]; if(ny < 0 || H <= ny || nx < 0 || W <= nx || v[ny][nx] == '#' || v[ny][nx] == '*' || gd[ny * W + nx] != INF) { continue; } gd[ny * W + nx] = gd[y * W + x] + 1; total_gd += gd[ny * W + nx]; que.push(ny * W + nx); } } vector<pll> d; int scnt = 0; double total_sd = 0; for(int i = 0; i < H * W; ++i) { if(i == g || v[i / W][i % W] == '*' || v[i / W][i % W] == '#') { continue; } if(gd[i] == INF && sd[i] != INF) { scnt++; total_sd += sd[i]; } else if(sd[i] != INF) { d.emplace_back(-gd[i] + sd[i], i); } } sort(d.begin(), d.end()); double res = 1e18; auto it = d.begin(); for(int i = -H * W; i <= H * W; ++i) { while(it != end(d) && it->first <= i) { scnt++; total_sd += sd[it->second]; total_gd -= gd[it->second]; it++; } if(scnt == fcnt) { continue; } double E = (total_gd + total_sd) / (1 - (double)scnt / fcnt) / fcnt; if(gd[s] == INF || -gd[s] + sd[s] <= i) { res = min(res, E + sd[s]); } else { res = min(res, (double)gd[s]); } } cout << fixed << setprecision(10) << res << endl; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
//?????°???????????????????????£???????????£???(orz) #include <iostream> #include <algorithm> #include <queue> #include <tuple> #include <vector> #include <cstdio> #include <string> #define int long long using namespace std; typedef tuple<int, int, int> T; const int dy[4] = {-1, 0, 1, 0}; const int dx[4] = {0, 1, 0, -1}; int h, w; int sy, sx; int gy, gx; string s[500]; int a[500][500]; //??????????????°????????§????????¢ int b[500][500]; //??´???????????§????????? int INF = 1145141919893810; signed main() { int i, j; cin >> w >> h; for (i = 0; i < h; i++) cin >> s[i]; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { if (s[i][j] == 's') { sy = i; sx = j; } if (s[i][j] == 'g') { gy = i; gx = j; } a[i][j] = INF; b[i][j] = INF; } } queue<T> que; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { if (s[i][j] == '*') { que.push(T(0, i, j)); a[i][j] = 0; } } } while (!que.empty()) { T now = que.front(); que.pop(); int cst = get<0>(now); int y = get<1>(now); int x = get<2>(now); for (i = 0; i < 4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; if (!(0 <= ny && ny < h && 0 <= nx && nx < w)) continue; if (s[ny][nx] == '#' || a[ny][nx] <= cst + 1) continue; que.push(T(cst + 1, ny, nx)); a[ny][nx] = cst + 1; } } que.push(T(0, gy, gx)); while (!que.empty()) { T now = que.front(); que.pop(); int cst = get<0>(now); int y = get<1>(now); int x = get<2>(now); for (i = 0; i < 4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; if (!(0 <= ny && ny < h && 0 <= nx && nx < w)) continue; if (s[ny][nx] == '#' || s[ny][nx] == '*' || b[ny][nx] <= cst + 1) continue; que.push(T(cst + 1, ny, nx)); b[ny][nx] = cst + 1; } } //????????? vector<T> cells; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { if (s[i][j] == '.' || s[i][j] == 's') { cells.push_back(T(b[i][j] - a[i][j], a[i][j], b[i][j])); } } } sort(cells.begin(), cells.end()); //(x?????°??????????????????????????????????????????(A)????????°. x + y????????????(B)????????°, E?????°??????????????§????????´???????????§??????????????°) //(Sx???A???g?????§????????????????????????, Hy???B-A?????°????????§??????????????????????????? //??? E = (Sx + Hy) / x //???????????????. ?????£???, (x, y)?????¨??¨?????????, E = (Sx + Hy) / x??¨??????????????¨?????????x, y????????????????????¨??£?????????????????????????±??????? //??£??????????????????????????????, E???????°????????±?????????°?????£??????E????±?????????? //???????????£??????E???????????????x = 0??????????????¨????????????????????????????????§???x > 0??¨????????? int Sx = 0; int Hy = 0; for (i = 0; i < cells.size(); i++) Hy += get<1>(cells[i]); double minE = INF; for (int x = 0; x <= cells.size(); x++) { if (x > 0) { double E = (Sx + Hy) / (double)x; double eps = 1e-10; if (get<0>(cells[x - 1]) - eps <= E && E <= get<0>(cells[x]) + eps) { minE = min(minE, E); } } Sx += get<2>(cells[x]); Hy -= get<1>(cells[x]); } //2??????????????? double ans = min((double)b[sy][sx], minE + a[sy][sx]); printf("%.14f\n", ans); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <string> #include <vector> #include<iostream> #include<cstdio> #include<cstdlib> #include<stack> #include<queue> #include<cmath> #include<algorithm> #include<functional> #include<list> #include<deque> #include<bitset> #include<set> #include<map> #include<cstring> #include<sstream> #include<complex> #include<iomanip> #include<numeric> #define X first #define Y second #define pb push_back #define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X)) #define rrep(X,Y) for (int (X) = (Y-1);(X) >=0;--(X)) #define repe(X,Y) for ((X) = 0;(X) < (Y);++(X)) #define peat(X,Y) for (;(X) < (Y);++(X)) #define all(X) (X).begin(),(X).end() #define rall(X) (X).rbegin(),(X).rend() //#define int long long using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,pii> piii; typedef pair<ll,ll> pll; template<class T> ostream& operator<<(ostream &os, const vector<T> &t) { os<<"{"; rep(i,t.size()) {os<<t[i]<<",";} os<<"}"<<endl; return os;} template<class S, class T> ostream& operator<<(ostream &os, const pair<S,T> &t) { return os<<"("<<t.first<<","<<t.second<<")";} ll d[512][512],INF=5e15,d2[512][512], dx[]={1,0,-1,0},dy[]={0,1,0,-1},dd[512][512]; int main(){ ios_base::sync_with_stdio(false); cout<<fixed<<setprecision(10); // cout<<sizeof(ll)<<endl; int i,j,k,n,m,sx,sy,gx,gy; cin>>m>>n; vector<string> mp(n); rep(i,n) cin>>mp[i]; fill(d[0],d[0]+512*512,INF); fill(d2[0],d2[0]+512*512,INF); queue<pii> que,que2; rep(i,n)rep(j,m){ if(mp[i][j]=='s'){ sx=j; sy=i; }else if(mp[i][j]=='g'){ gx=j; gy=i; que.push(pii(j,i)); d[i][j]=0; }else if(mp[i][j]=='*'){ que2.push(pii(j,i)); d2[i][j]=0; } } while(!que.empty()){ pii p=que.front();que.pop(); rep(i,4){ int x=p.X+dx[i],y=p.Y+dy[i]; if(mp[y][x]!='#' && mp[y][x]!='*' && d[y][x]>d[p.Y][p.X]+1){ d[y][x]=d[p.Y][p.X]+1; que.push(pii(x,y)); } } } while(!que2.empty()){ pii p=que2.front();que2.pop(); rep(i,4){ int x=p.X+dx[i],y=p.Y+dy[i]; if(mp[y][x]!='#' && d2[y][x]>d2[p.Y][p.X]+1){ d2[y][x]=d2[p.Y][p.X]+1; que2.push(pii(x,y)); } } } // rep(i,n){rep(j,m)cout<<d[i][j]<<",";cout<<endl;}cout<<endl; // rep(i,n){rep(j,m)cout<<d2[i][j]<<",";cout<<endl;} priority_queue<piii> q; ll a=0,b=0,nn=0; rep(i,n)rep(j,m){ if(mp[i][j]!='#' && mp[i][j]!='*' && mp[i][j]!='g'){ q.push(piii(d[i][j]-d2[i][j],pii(j,i))); b+=d[i][j]; nn++; } } // cout<<b<<","<<nn<<":"<<1.*b/(nn-a)<<endl; //cout<<d[sy][sx]*(1-dd[sy][sx])+(d2[sy][sx]+1.*b/(nn-a))*dd[sy][sx]<<endl; while(!q.empty()){ piii tmp=q.top();q.pop(); if(nn-a==1)break; if(tmp.X<1.*(b)/(nn-a)) break; //cout<<tmp.Y<<tmp.X+d2[tmp.Y.Y][tmp.Y.X]<<"->"; pii p=tmp.Y; b-=tmp.X; ++a; dd[p.Y][p.X]=1; // cout<<1.*b/(nn-1)+d2[tmp.Y.Y][tmp.Y.X]<<endl; //cout<<a<<","<<b<<endl; } cout<<d[sy][sx]*(1-dd[sy][sx])+(d2[sy][sx]+1.*b/(nn-a))*dd[sy][sx]<<endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <vector> #include <map> #include <queue> #include <tuple> #include <functional> #include <cstdio> #include <cmath> #define repeat(i,n) for (int i = 0; (i) < (n); ++(i)) template <class T> bool setmax(T & l, T const & r) { if (not (l < r)) return false; l = r; return true; } template <class T> bool setmin(T & l, T const & r) { if (not (r < l)) return false; l = r; return true; } using namespace std; const int inf = 1e9+7; const int dy[] = { -1, 1, 0, 0 }; const int dx[] = { 0, 0, 1, -1 }; int main() { // input int w, h; cin >> w >> h; vector<string> c(h); repeat (y,h) cin >> c[y]; // modify input int sy, sx, gy, gx; repeat (y,h) repeat (x,w) { if (c[y][x] == 's') { sy = y; sx = x; c[y][x] = '.'; } else if (c[y][x] == 'g') { gy = y; gx = x; } } // prepare auto on_field = [&](int y, int x) { return 0 <= y and y < h and 0 <= x and x < w; }; typedef queue<pair<int,int> > points_queue; auto bfs = [&](function<void (points_queue &)> init, function<void (points_queue &, int, int, int, int)> update) { points_queue que; init(que); while (not que.empty()) { int y, x; tie(y, x) = que.front(); que.pop(); repeat (i,4) { int ny = y + dy[i]; int nx = x + dx[i]; if (not on_field(ny, nx)) continue; if (c[ny][nx] != '.') continue; update(que, y, x, ny, nx); } } }; vector<vector<int> > goal(h, vector<int>(w, inf)); bfs([&](points_queue & que) { goal[gy][gx] = 0; que.push(make_pair(gy, gx)); }, [&](points_queue & que, int y, int x, int ny, int nx) { if (goal[ny][nx] == inf) { goal[ny][nx] = goal[y][x] + 1; que.push(make_pair(ny, nx)); } }); vector<vector<int> > jump(h, vector<int>(w, inf)); bfs([&](points_queue & que) { repeat (y,h) repeat (x,w) if (c[y][x] == '*') { jump[y][x] = 0; que.push(make_pair(y, x)); } }, [&](points_queue & que, int y, int x, int ny, int nx) { if (jump[ny][nx] == inf) { jump[ny][nx] = jump[y][x] + 1; que.push(make_pair(ny, nx)); } }); map<pair<int,int>,int> freq; // frequency int total = 0; int max_goal = 0; repeat (y,h) repeat (x,w) if (c[y][x] == '.') { freq[make_pair(goal[y][x], jump[y][x])] += 1; total += 1; if (goal[y][x] < inf) setmax(max_goal, goal[y][x]); } // calc long double e = INFINITY; repeat (estimate, max_goal + 1) { // E = f(E) = aE + b long double a = 0; long double b = 0; for (auto it : freq) { int g, s; tie(g, s) = it.first; int cnt = it.second; long double p = cnt /(long double) total; if (g == inf) { a += p; b += p * s; } else if (s == inf) { b += p * g; } else { if (g <= s + estimate) { b += p * g; } else { a += p; b += p * s; } } } setmin(e, b / (1 - a)); } // output long double ans = goal[sy][sx] == inf ? jump[sy][sx] + e : jump[sy][sx] == inf ? goal[sy][sx] : min<long double>(goal[sy][sx], jump[sy][sx] + e); // the answer can become grater than `int inf`, so conditional op. is required. printf("%.12Lf\n", ans); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> /* */ using namespace std; typedef pair<long long int, pair<long long int, long long int>>one; #define mod 1000000007LL int main() { long long int W, H; cin >> W >> H; vector<string>D( H ); long long int counttile = 0; pair<long long int, long long int>start, goal; vector<pair<long long int, long long int>>warp; vector<vector<pair<long long int, long long int>>>len( H, vector<pair<long long int, long long int>>( W, make_pair( LLONG_MAX / 500 / 500 / 500, LLONG_MAX / 500 / 500 / 500 ) ) ); vector<pair<long long int, long long int>>tile; for( size_t i = 0; i < H; i++ ) { cin >> D[i]; for( size_t j = 0; j < D[i].length(); j++ ) { if( D[i][j] == 's' ) { D[i][j] = '.'; tile.push_back( make_pair( i, j ) ); start.first = i; start.second = j; counttile++; } else if( D[i][j] == 'g' ) { goal.first = i; goal.second = j; } else if( D[i][j] == '*' ) { warp.push_back( make_pair( i, j ) ); } else if( D[i][j] == '.' ) { counttile++; tile.push_back( make_pair( i, j ) ); } } } int dx[] = {0,1,0,-1}; int dy[] = {1,0,-1,0}; { priority_queue<one, vector<one>, greater<one>>que; que.push( make_pair( 0, goal ) ); while( que.size() ) { auto now = que.top(); que.pop(); for( size_t i = 0; i < 4; i++ ) { auto next = now; next.first++; next.second.first += dx[i]; next.second.second += dy[i]; if( 0 <= next.second.first&&next.second.first < H && 0 <= next.second.second &&next.second.second < W ) { if( D[next.second.first][next.second.second] == '.' ) { if( len[next.second.first][next.second.second].first > next.first ) { len[next.second.first][next.second.second].first = next.first; que.push( next ); } } } } } } queue<one>que; for( auto x : warp ) { que.push( make_pair( 0, x ) ); } while( que.size() ) { auto now = que.front(); que.pop(); if( len[now.second.first][now.second.second].second < now.first ) { continue; } for( size_t i = 0; i < 4; i++ ) { auto next = now; next.first++; next.second.first += dx[i]; next.second.second += dy[i]; if( 0 <= next.second.first&&next.second.first < H && 0 <= next.second.second &&next.second.second < W ) { if( D[next.second.first][next.second.second] == '.' ) { if( len[next.second.first][next.second.second].second > next.first ) { len[next.second.first][next.second.second].second = next.first; que.push( next ); } } } } } long double maxExpectedValue = W*H*100000, minExpectedValue = 0; for( size_t indexindex = 0; indexindex < 16300; indexindex++ ) { long double midExpectedValue = ( maxExpectedValue + minExpectedValue ) / 2.L; //cout << fixed << setprecision( 20 ) << maxExpectedValue << " " << minExpectedValue << endl; long double countExpectedValue = 0; for( auto point : tile ) { long long int i = point.first, j = point.second; countExpectedValue += min( 1.L* len[i][j].first, len[i][j].second + midExpectedValue ); } countExpectedValue /= counttile; if( midExpectedValue < countExpectedValue ) { minExpectedValue = midExpectedValue; } else { maxExpectedValue = midExpectedValue; } } //cout << fixed << setprecision( 20 ) << 1.L* len[start.first][start.second].first << " " << len[start.first][start.second].second + maxExpectedValue << endl; cout << fixed << setprecision( 20 ) << min( 1.L* len[start.first][start.second].first, len[start.first][start.second].second + maxExpectedValue ) << endl; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <vector> #include <string> #include <cmath> #include <algorithm> #include <utility> #include <queue> #include <set> #include <map> #include <iomanip> using namespace std; typedef long long ll; typedef pair<int,int> PII; typedef vector<int> VI; typedef vector<VI> VVI; #define MP make_pair #define PB push_back #define inf 100000000000000007 typedef long double ld; int dx[] = {1,-1,0,0}; int dy[] = {0,0,1,-1}; int w,h; ld sp_calc(vector<string> &v,vector<vector<ld> > &dp){ ld ans = 0; ld d = 0.0; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(v[i][j]=='.'){ d += 1.0; ans += dp[i][j]; } } } ans /= d; return ans; } int main(){ cin >> w >> h; vector<string> v(h); for(int i=0;i<h;i++){ cin >> v[i]; } vector<vector<ld> > d1(h,vector<ld>(w,inf)),d2(h,vector<ld>(w,inf)),dp(h,vector<ld>(w)); queue<pair<int,int> > q1,q2; int x_s,y_s; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(v[i][j]=='g'){ d1[i][j] = 0.0; q1.push(MP(i,j)); } if(v[i][j]=='*'){ d2[i][j] = 0.0; q2.push(MP(i,j)); } if(v[i][j]=='s'){ x_s = i; y_s = j; v[i][j] = '.'; } } } while(!q1.empty()){ pair<int,int> p; p = q1.front(); q1.pop(); int x,y; x = p.first; y = p.second; for(int i=0;i<4;i++){ if(v[x+dx[i]][y+dy[i]]=='.'){ if(d1[x+dx[i]][y+dy[i]]==inf){ d1[x+dx[i]][y+dy[i]] = d1[x][y]+1.0; q1.push(MP(x+dx[i],y+dy[i])); } } } } while(!q2.empty()){ pair<int,int> p; p = q2.front(); q2.pop(); int x,y; x = p.first; y = p.second; for(int i=0;i<4;i++){ if(v[x+dx[i]][y+dy[i]]=='.'){ if(d2[x+dx[i]][y+dy[i]]==inf){ d2[x+dx[i]][y+dy[i]] = d2[x][y]+1.0; q2.push(MP(x+dx[i],y+dy[i])); } } } } if(d2[x_s][y_s]==inf){ cout << fixed << setprecision(15) << d1[x_s][y_s] << endl; return 0; } ld up = 100000000000.0; ld low = 0.0; ld mid; int counter = 0; while(1){ counter++; if(counter >1000)break; mid = (up+low)/2.0; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ dp[i][j] = 0.0; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(d1[i][j]<d2[i][j]+mid){ dp[i][j] = d1[i][j]; }else{ dp[i][j] = d2[i][j]+mid; } } } if(sp_calc(v,dp)>mid){ low = mid; }else{ up = mid; } } cout << fixed << setprecision(15) << dp[x_s][y_s] << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} template<class T> inline T sqr(T x) {return x*x;} typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<int, int> pii; typedef long long ll; #define all(a) (a).begin(),(a).end() #define rall(a) (a).rbegin(), (a).rend() #define pb push_back #define mp make_pair #define each(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i) #define exist(s,e) ((s).find(e)!=(s).end()) #define range(i,a,b) for(int i=(a);i<(b);++i) #define rep(i,n) range(i,0,n) #define clr(a,b) memset((a), (b) ,sizeof(a)) #define dump(x) cerr << #x << " = " << (x) << endl; #define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; const double eps = 1e-10; const double pi = acos(-1.0); const ll INF =1LL << 62; const int inf =1 << 18; const int cmax=250010; int w,h; ll d[cmax]; ll e[cmax]; struct state{ int d,e; bool operator<(const state &arg)const{ return (d-e) > (arg.d-arg.e); } }; string table[510]; int n=0; state ex[cmax]; void dijkstra(char s,char o,ll* dist){ rep(i,cmax) dist[i]=inf; queue<pii> q; rep(i,h)rep(j,w){ if(table[i][j]==s){ int idx=w*i+j; dist[idx]=0; pii in=mp(idx,0); q.push(in); } } while(!q.empty()){ pii cur=q.front();q.pop(); if(dist[cur.first]<cur.second) continue; int dir[4]={-w,-1,1,w}; rep(i,4){ pii next=cur; next.first+=dir[i]; next.second++; int cw=next.first%w; int ch=next.first/w; if(table[ch][cw]=='#'||table[ch][cw]==o) continue; if(dist[next.first]>next.second){ dist[next.first]=next.second; q.push(next); } } } return; } int main(void){ cin >> w >> h; rep(i,h) cin >> table[i]; dijkstra('g','*',d); dijkstra('*','#',e); int sidx; ll dsum=0; ll esum=0; rep(i,h)rep(j,w) { int idx=i*w+j; if(table[i][j]=='.'||table[i][j]=='s'){ if(d[idx]!=inf){ ex[n].d=d[idx]; ex[n++].e=e[idx]; }else esum+=e[idx]; } if(table[i][j]=='s') sidx=idx; } sort(ex,ex+n); rep(i,n) dsum+=ex[i].d; double ans=(1.0*(dsum+esum)/n+e[sidx]); for(int i=n;i>=1;--i){ ans=min(ans,1.0*(dsum+esum)/i+e[sidx]); int cur=n-i; dsum-=ex[cur].d; dsum+=ex[cur].e; } if(d[sidx]!=inf) ans=min(ans,1.0*d[sidx]); cout.precision(16); cout << fixed << ans << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <valarray> #include <vector> #define EPS 1e-9 #define INF (1070000000LL*1070000000LL) #define MOD 1000000007LL #define fir first #define foreach(it,X) for(__typeof((X).begin()) it=(X).begin();it!=(X).end();it++) #define ite iterator #define mp make_pair #define rep(i,n) rep2(i,0,n) #define rep2(i,m,n) for(int i=m;i<(n);i++) #define pb push_back #define sec second #define sz(x) ((int)(x).size()) using namespace std; struct timer{ time_t start; timer(){start=clock();} ~timer(){cerr<<1.*(clock()-start)/CLOCKS_PER_SEC<<" secs"<<endl;} }; typedef istringstream iss; typedef long long ll; typedef pair<int,int> pi; typedef stringstream sst; typedef vector<int> vi; int H,W; char c[555][555]; int sy,sx,gy,gx; ll dist1[555][555],dist2[555][555]; int dy[]={0,1,0,-1}; int dx[]={1,0,-1,0}; int main(){ //cin.tie(0); //ios_base::sync_with_stdio(0); cin>>W>>H; rep(i,H)rep(j,W){ cin>>c[i][j]; if(c[i][j]=='s')sy=i,sx=j,c[i][j]='.'; if(c[i][j]=='g')gy=i,gx=j; } rep(i,H)rep(j,W){ dist1[i][j]=dist2[i][j]=INF; } dist1[gy][gx]=0; queue<pi> Q; Q.push(mp(gy,gx)); while(sz(Q)){ pi p=Q.front();Q.pop(); int y=p.fir,x=p.sec; rep(d,4){ int ny=y+dy[d],nx=x+dx[d]; if(c[ny][nx]=='.' && dist1[ny][nx]==INF){ dist1[ny][nx]=dist1[y][x]+1; Q.push(mp(ny,nx)); } } } rep(i,H)rep(j,W)if(c[i][j]=='*'){ dist2[i][j]=0; Q.push(mp(i,j)); } while(sz(Q)){ pi p=Q.front();Q.pop(); int y=p.fir,x=p.sec; rep(d,4){ int ny=y+dy[d],nx=x+dx[d]; if(c[ny][nx]=='.' && dist2[ny][nx]==INF){ dist2[ny][nx]=dist2[y][x]+1; Q.push(mp(ny,nx)); } } } vector<ll> d1,d2; int start; rep(i,H)rep(j,W)if(c[i][j]=='.'){ if(i==sy && j==sx)start=sz(d1); d1.pb(dist1[i][j]); d2.pb(dist2[i][j]); } long double lo=0,hi=1e15; rep(t,100){ long double mi=(lo+hi)/2; long double sum=0; rep(i,sz(d1)){ sum+=min((long double)d1[i],d2[i]+mi); } if(sum>mi*sz(d1))lo=mi; else hi=mi; } printf("%.16f\n",min((double)d1[start],(double)(d2[start]+hi))); }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <vector> #include <algorithm> #include <queue> #include <iomanip> using namespace std; const int inf = 1e9; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; void bfs_grid(queue<pair<int,int>> &wait, vector<string> &g, vector<vector<int>> &res){ while(!wait.empty()){ int y = wait.front().first; int x = wait.front().second; wait.pop(); for(int d=0; d<4; d++){ int ny = y +dy[d]; int nx = x +dx[d]; if(g[ny][nx] == '#' or g[ny][nx] == '*') continue; if(res[ny][nx] != inf) continue; res[ny][nx] = res[y][x] +1; wait.push({ny, nx}); } } } int main(){ int w,h; cin >> w >> h; vector<string> g(h); for(int i=0; i<h; i++){ cin >> g[i]; } int sy,sx,gy,gx; queue<pair<int, int>> wait; int n = 0; vector<vector<int>> mincost_spring(h, vector<int>(w, inf)); for(int i=0; i<h; i++){ for(int j=0; j<w; j++){ if(g[i][j] == 's'){ sy = i; sx = j; g[i][j] = '.'; } if(g[i][j] == 'g'){ gy = i; gx = j; } if(g[i][j] == '*'){ wait.push({i, j}); mincost_spring[i][j] = 0; } if(g[i][j] == '.'){ n++; } } } bfs_grid(wait, g, mincost_spring); vector<vector<int>> mincost_goal(h, vector<int>(w, inf)); mincost_goal[gy][gx] = 0; wait.push({gy, gx}); bfs_grid(wait, g, mincost_goal); long double lb=0, ub=1LL<<60; for(int rep=0; rep<100; rep++){ long double mid = (lb +ub) /2; long double sum = 0; for(int i=0; i<h; i++){ for(int j=0; j<w; j++){ if(g[i][j] != '.') continue; long double tmp = 1e18; if(mincost_goal[i][j] != inf){ tmp = min(tmp, (long double)mincost_goal[i][j]); } if(mincost_spring[i][j] != inf){ tmp = min(tmp, mincost_spring[i][j] +mid); } sum += tmp; } } if(n*mid > sum){ ub = mid; }else{ lb = mid; } } long double ans = 1e18; if(mincost_goal[sy][sx] != inf){ ans = min(ans, (long double)mincost_goal[sy][sx]); } if(mincost_spring[sy][sx] != inf){ ans = min(ans, mincost_spring[sy][sx] +lb); } cout << fixed << setprecision(12); cout << ans << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args) { new Main().solver(); } int[] dx = { 1, -1, 0, 0 }; int[] dy = { 0, 0, 1, -1 }; char[][] table; long INF = 1L << 50; int h, w; void solver() { Scanner sc = new Scanner(System.in); w = sc.nextInt(); h = sc.nextInt(); int sx = -1, sy = -1, gx = -1, gy = -1; double n = 0; table = new char[h][w]; long[][] distance_from_goal = new long[h][w]; long[][] distance_from_spring = new long[h][w]; ArrayDeque<Pair> que1 = new ArrayDeque<>(); ArrayDeque<Pair> que2 = new ArrayDeque<>(); for (int i = 0; i < h; i++) { table[i] = sc.next().toCharArray(); Arrays.fill(distance_from_goal[i], INF); Arrays.fill(distance_from_spring[i], INF); for (int j = 0; j < w; j++) { if (table[i][j] == 's') { sx = j; sy = i; n++; } else if (table[i][j] == 'g') { gx = j; gy = i; distance_from_goal[gy][gx] = 0; } else if (table[i][j] == '.') n++; else if (table[i][j] == '*') { distance_from_spring[i][j] = 0; que2.add(new Pair(j, i)); } } } que1.add(new Pair(gx, gy)); while (!que1.isEmpty()) { Pair p = que1.poll(); for (int i = 0; i < 4; i++) { int nx = p.x + dx[i]; int ny = p.y + dy[i]; if (on_filed(nx, ny) && distance_from_goal[ny][nx] > distance_from_goal[p.y][p.x] + 1) { distance_from_goal[ny][nx] = distance_from_goal[p.y][p.x] + 1; if (table[ny][nx] == '.' || table[ny][nx] == 's') que1.add(new Pair(nx, ny)); } } } while (!que2.isEmpty()) { Pair p = que2.poll(); for (int i = 0; i < 4; i++) { int nx = p.x + dx[i]; int ny = p.y + dy[i]; if (on_filed(nx, ny) && distance_from_spring[ny][nx] > distance_from_spring[p.y][p.x] + 1) { distance_from_spring[ny][nx] = distance_from_spring[p.y][p.x] + 1; if (table[ny][nx] == '.' || table[ny][nx] == 's') que2.add(new Pair(nx, ny)); } } } double a = 0, b = 0; ArrayList<P> list = new ArrayList<>(); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (table[i][j] == '.' || table[i][j] == 's') { if (distance_from_goal[i][j] >= INF) { a += distance_from_spring[i][j]; b++; continue; } else { a += distance_from_goal[i][j]; if (distance_from_spring[i][j] >= (1 << 30) || distance_from_goal[i][j] <= distance_from_spring[i][j]) { continue; } else list.add(new P(distance_from_goal[i][j], distance_from_spring[i][j])); } } } } list.sort(null); // E=a+bE double e = a / (n - b); for (int i = 0; i < list.size(); i++) { a -= list.get(i).d_goal; a += list.get(i).d_spring; b++; if (i + 1 < list.size() && list.get(i).diff == list.get(i + 1).diff) continue; e = Math.min(e, (a / (n - b))); } System.out.println(Math.min(distance_from_goal[sy][sx], e + distance_from_spring[sy][sx])); } boolean on_filed(int x, int y) { if (0 <= x && x < w && 0 <= y && y < h && table[y][x] != '#') return true; else return false; } class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } class P implements Comparable<P> { long d_goal; long d_spring; long diff; public P(long d_goal, long d_spring) { this.d_goal = d_goal; this.d_spring = d_spring; diff = d_goal - d_spring; } @Override public int compareTo(P o) { return -Long.compare(this.diff, o.diff); } } void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
JAVA
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; #define reep(i,a,b) for(int i=(a);i<(b);i++) #define rep(i,n) reep((i),0,(n)) #define PB push_back #define mkp make_pair #define F first #define S second #define INF 0x3f3f3f3f #define EPS 1e-8 typedef vector<int> vint; typedef pair<int,int> pii; int main(){ int H,W; cin>>W>>H; vector<string> v(H); rep(i,H) cin>>v[i]; vector<vint> vv1(H,vint(W,INF)); vector<vint> vv2(H,vint(W,INF)); pii s; queue<pii> q1,q2; long double p = 0; rep(i,H){ rep(j,W){ if(v[i][j] == 'g'){ q1.push(pii(i,j)); } else if(v[i][j] == 's'){ s=pii(i,j); v[i][j] = '.'; p+=1.0; } else if(v[i][j] == '*'){ q2.push(pii(i,j)); } else if(v[i][j] == '.'){ p+=1.0; } } } p=1/p; int cnt = 0; int dd[]={0,1,0,-1,0}; while(q1.size()){ int qs = q1.size(); rep(i,qs){ pii top = q1.front(); q1.pop(); if(vv1[top.F][top.S]!=INF) continue; vv1[top.F][top.S] = cnt; rep(j,4){ pii nex = top; nex.F += dd[j]; nex.S += dd[j+1]; if(v[nex.F][nex.S] == '#') continue; if(v[nex.F][nex.S] == '*') continue; q1.push(nex); } } cnt++; } cnt = 0; while(q2.size()){ int qs = q2.size(); rep(i,qs){ pii top = q2.front(); q2.pop(); if(vv2[top.F][top.S]!=INF) continue; vv2[top.F][top.S] = cnt; rep(j,4){ pii nex = top; nex.F += dd[j]; nex.S += dd[j+1]; if(v[nex.F][nex.S] == '#') continue; if(v[nex.F][nex.S] == '*') continue; q2.push(nex); } } cnt++; } int maxn = 0; rep(i,H) rep(j,W){ if(vv1[i][j] != INF) maxn=max(maxn,vv1[i][j]); } map<pair<int,int>,int> ma; double bb = 0; rep(i,H){ rep(j,W){ if(v[i][j] != '.') continue; int x = vv1[i][j]; int y = vv2[i][j]; int t = min(x,y); bb += t*p; x-=t; y-=t; pii z = pii(x,y); if(ma.count(z)==0) ma[z] = 0; ma[z]+=1; } } long double ans = 1e100; rep(o,maxn+1){ long double a = 0; long double b = bb; for(auto x:ma){ if(x.F.F-x.F.S <= o){ b += p*x.F.F*x.S; } else{ b += p*x.F.S*x.S; a += p*x.S; } } long double e = b/(1-a); long double tmp; if(vv1[s.F][s.S]-vv2[s.F][s.S] <= o) tmp = vv1[s.F][s.S]; else tmp = vv2[s.F][s.S] + e; ans = min(ans,tmp); } cout<<fixed<<setprecision(20); cout<<ans<<endl; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<(n);i++) #define pb push_back #define all(v) (v).begin(),(v).end() #define fi first #define se second typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;} template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;} #define double long double const int INF=1001001001; const int INFLL=1001001001001001001ll; const int mod=1000000007; inline void add(int &a,int b){ a+=b; if(a>=mod)a-=mod; } int dy[4]={-1,0,1,0}; int dx[4]={0,-1,0,1}; int H,W; char fld[555][555]; double E[555][555]; bool check(double e){ queue<pint>que; fill_n(*E,555*555,1e14); rep(i,H)rep(j,W)if(fld[i][j]=='g'){ E[i][j]=0; que.push({i,j}); } bool flag=false; while(true){ if(que.size()==0){ if(flag)break; rep(i,H)rep(j,W)if(fld[i][j]=='*'){ E[i][j]=e; que.push({i,j}); } flag=true; continue; } int y,x; tie(y,x)=que.front(); que.pop(); if(E[y][x]+1>=e&&!flag){ rep(i,H)rep(j,W)if(fld[i][j]=='*'){ E[i][j]=e; que.push({i,j}); } flag=true; } rep(d,4){ int ny=y+dy[d],nx=x+dx[d]; if(fld[ny][nx]=='#'||fld[ny][nx]=='*')continue; if(E[ny][nx]!=1e14)continue; E[ny][nx]=E[y][x]+1; que.push({ny,nx}); } } double sum=0; int cnt=0; rep(i,H)rep(j,W){ if(fld[i][j]=='#'||fld[i][j]=='*'||fld[i][j]=='g')continue; cnt++;sum+=E[i][j]; } return sum<=e*cnt; } signed main(){ cin>>W>>H; rep(i,H)cin>>fld[i]; vector<vint>dist(H,vint(W,INT_MAX)); queue<pint>que; rep(i,H)rep(j,W)if(fld[i][j]=='s'){ dist[i][j]=0; que.push({i,j}); } bool flag=false; while(que.size()){ int y,x; tie(y,x)=que.front(); que.pop(); rep(d,4){ int ny=y+dy[d],nx=x+dx[d]; if(fld[ny][nx]=='#'||dist[ny][nx]!=INT_MAX)continue; if(fld[ny][nx]=='*')flag=true; dist[ny][nx]=dist[y][x]+1; que.push({ny,nx}); } } if(!flag){ rep(i,H)rep(j,W)if(fld[i][j]=='g'){ printf("%.20Lf\n",(double)dist[i][j]); return 0; } } double lb=0,ub=1e12; rep(i,200){ double mid=(ub+lb)/2; if(check(mid))ub=mid; else lb=mid; } rep(i,H)rep(j,W){ if(fld[i][j]=='s'){ printf("%.20Lf\n",E[i][j]); } } return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-10) #define equals(a,b) (fabs((a)-(b))<EPS) using namespace std; typedef long double ld; const int MAX = 501,IINF = INT_MAX; const ld LDINF = 1e100; int H,W,sx,sy,gx,gy; ld mincost[MAX][MAX][2]; // mincost[][][0] => from start, [1] = > from star char c[MAX][MAX]; bool ban[MAX][MAX]; vector<int> star,plane; int dx[] = {0,1,0,-1}; int dy[] = {1,0,-1,0}; inline bool isValid(int x,int y) { return 0 <= x && x < W && 0 <= y && y < H; } inline void bfs(vector<int> sp,vector<int> Forbidden,int type){ rep(i,H)rep(j,W) mincost[i][j][type] = LDINF, ban[i][j] = false; queue<int> que; rep(i,(int)sp.size()) que.push(sp[i]), mincost[sp[i]/W][sp[i]%W][type] = 0; rep(i,(int)Forbidden.size()) ban[Forbidden[i]/W][Forbidden[i]%W] = true; while(!que.empty()){ int cur = que.front(); que.pop(); rep(i,4){ int nx = cur % W + dx[i], ny = cur / W + dy[i]; if( c[ny][nx] == '#' ) continue; if( ban[ny][nx] ) continue; if( mincost[ny][nx][type] == LDINF ) { mincost[ny][nx][type] = mincost[cur/W][cur%W][type] + 1; que.push(nx+ny*W); } } } } bool check(ld E){ ld T = 0; rep(i,(int)plane.size()){ int x = plane[i] % W, y = plane[i] / W; T += min(mincost[y][x][0],mincost[y][x][1]+E); } ld len = plane.size(); return len * E > T; } int main(){ cin >> W >> H; rep(i,H)rep(j,W){ cin >> c[i][j]; if( c[i][j] == 's' ) sx = j, sy = i, c[i][j] = '.'; if( c[i][j] == 'g' ) gx = j, gy = i; if( c[i][j] == '*' ) star.push_back(j+i*W); if( c[i][j] == '.' ) plane.push_back(j+i*W); } vector<int> sp,forbidden; sp.push_back(gx+gy*W); forbidden = star; forbidden.push_back(gx+gy*W); bfs(sp,forbidden,0); sp = star; forbidden.push_back(gx+gy*W); //forbidden.clear(); bfs(sp,forbidden,1); ld L = 0, R = 1e50, M = 0; rep(i,220){ M = ( L + R ) * (ld)0.5; if( check(M) ) R = M; else L = M; } cout << setiosflags(ios::fixed) << setprecision(20) << min((ld)mincost[sy][sx][0],(ld)mincost[sy][sx][1]+L) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> using namespace std; typedef long long ll; int H,W; int dy[]={-1,0,1,0}; int dx[]={0,1,0,-1}; char t[500][500]; ll A[500][500],B[500][500]; ll INF=(1LL<<50); void bfs(char ch,ll d[500][500]){ fill(d[0],d[500], INF ); queue<int> qy,qx; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(ch==t[i][j]){ d[i][j]=0; qy.push(i); qx.push(j); } } } while(!qy.empty()){ int y=qy.front();qy.pop(); int x=qx.front();qx.pop(); for(int dir=0;dir<4;dir++){ int ny=y+dy[dir]; int nx=x+dx[dir]; if(t[ny][nx]=='#')continue; if(t[ny][nx]=='*')continue; if(d[ny][nx]>d[y][x]+1){ d[ny][nx]=d[y][x]+1; qy.push(ny); qx.push(nx); } } } } int main(){ std::ios::sync_with_stdio(false); std::cin.tie(0); cin>>W>>H; for(int i=0;i<H;i++) for(int j=0;j<W;j++) cin>>t[i][j]; bfs('*',A); bfs('g',B); vector<ll> v; ll sum=0,cnt=0,K=0; double base=1e100; double ans=1e100; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(t[i][j]=='#')continue; if(t[i][j]=='*')continue; if(t[i][j]=='g')continue; cnt++; if(t[i][j]=='s'){ if(A[i][j]==INF)base=1e100; else base=A[i][j]; if(B[i][j]!=INF)ans=B[i][j]; } if(A[i][j]==INF){ sum+=B[i][j]; }else if(B[i][j]==INF){ sum+=A[i][j]; K++; }else{ sum+=B[i][j]; v.push_back(A[i][j]-B[i][j]); } } } sort(v.begin(),v.end()); for(int i=0;i<=(int)v.size();i++){ double rate=(double)K/(double)cnt; double X=(double)sum/(double)cnt; X/=(1.0-rate); ans=min(ans,(double)base+X); K++; if(i==(int)v.size())break; sum+=v[i]; } printf("%.12f\n",ans); return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> using namespace std; using ll=long long; using ld=long double; using P=pair<ll,ll>; #define MOD 1000000007ll #define INF 1000000000ll #define EPS 1e-10 #define FOR(i,n,m) for(ll i=n;i<(ll)m;i++) #define REP(i,n) FOR(i,0,n) #define DUMP(a) REP(d,a.size()){cout<<a[d];if(d!=a.size()-1)cout<<" ";else cout<<endl;} #define ALL(v) v.begin(),v.end() #define UNIQUE(v) sort(v.begin(),v.end());v.erase(unique(v.begin(),v.end()),v.end()); #define pb push_back P dlt[4]={P(1,0),P(0,1),P(-1,0),P(0,-1)}; vector<vector<char>> c; ll h,w,f; P sp,gp; vector<P> spr; vector<vector<ll>> g_cost; vector<vector<ll>> s_cost; bool isfloor(P p) { if(p.first>=0&&p.first<h&&p.second>=0&&p.second<w&& (c[p.first][p.second]=='.'||c[p.first][p.second]=='s')) return true; else return false; } vector<vector<ll>> dijkstra(vector<P> s) { vector<vector<ll>> dst(h,vector<ll>(w,INF*INF)); priority_queue<pair<ll,P>,vector<pair<ll,P>>,greater<pair<ll,P>>> q; REP(i,(ll)s.size()) { dst[s[i].first][s[i].second]=0; q.push(make_pair(0,s[i])); } while(!q.empty()) { ll d=q.top().first; P p=q.top().second; q.pop(); if(dst[p.first][p.second]!=d) continue; REP(i,4) { P np=P(p.first+dlt[i].first,p.second+dlt[i].second); if(isfloor(np)&&dst[np.first][np.second]>d+1) { dst[np.first][np.second]=d+1; q.push(make_pair(dst[np.first][np.second],np)); } } } return dst; } void init() { cin>>w>>h; c.assign(h,vector<char>(w)); REP(i,h) REP(j,w) cin>>c[i][j]; REP(i,h) REP(j,w) if(c[i][j]=='.'||c[i][j]=='s') f++; REP(i,h) REP(j,w) if(c[i][j]=='s') sp=P(i,j); REP(i,h) REP(j,w) if(c[i][j]=='g') gp=P(i,j); REP(i,h) REP(j,w) if(c[i][j]=='*') spr.pb(P(i,j)); g_cost=dijkstra(vector<P>(1,gp)); s_cost=dijkstra(spr); } int main(){ cin.tie(0); ios::sync_with_stdio(false); init(); if(g_cost[sp.first][sp.second]<=s_cost[sp.first][sp.second]) { cout<<fixed<<setprecision(39)<<g_cost[sp.first][sp.second]<<endl; return 0; } ll cons=0; ll cf=0; priority_queue<ll,vector<ll>,greater<ll>> diff; REP(i,h) REP(j,w) if(c[i][j]=='.'||c[i][j]=='s') { if(g_cost[i][j]==INF*INF) { cons+=s_cost[i][j]; cf++; continue; } cons+=g_cost[i][j]; if(s_cost[i][j]<g_cost[i][j]) diff.push(s_cost[i][j]-g_cost[i][j]); } ld min_x=cons/(ld)(f-cf); while(!diff.empty()) { ll c=diff.top(); diff.pop(); cons+=c; cf++; min_x=min(min_x,cons/(ld)(f-cf)); } cout<<fixed<<setprecision(39)<<min( (ld)g_cost[sp.first][sp.second],s_cost[sp.first][sp.second]+min_x)<<endl; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> using namespace std; struct cww{cww(){ ios::sync_with_stdio(false);cin.tie(0); cout<<fixed<<setprecision(10); }}init; inline bool isWall(char c){return c=='#';} inline bool isSpring(char c){return c=='*';} inline bool isFloor(char c){return c=='.'||c=='s';} inline bool isStart(char c){return c=='s';} inline bool isGoal(char c){return c=='g';} template<typename T> istream& operator>>(istream& is,vector<T>& v){ for(auto &it:v)is>>it; return is; } typedef long long LL; using P=pair<int,int>; typedef vector<LL> V; typedef vector<V> VV; const LL INF=1e12; const int dir4[]={0,1,0,-1,0}; int main(){ int R,C; cin>>C>>R; vector<string> maze(R); int sr,sc,gr,gc,M=0; cin>>maze; queue<P> que; VV dG(R,V(C,INF)); VV dB(R,V(C,INF)); for(int r=0;r<R;r++) for(int c=0;c<C;c++){ if(isSpring(maze[r][c])){ dB[r][c]=0; que.push(P(r,c)); } if(isFloor(maze[r][c])){ M++; } if(isStart(maze[r][c])){ sr=r,sc=c; } if(isGoal(maze[r][c])){ gr=r,gc=c; } } while(que.size()){ int r,c; tie(r,c)=que.front(); for(int i=0;i<4;i++){ int nr=r+dir4[i]; int nc=c+dir4[i+1]; if(isWall(maze[nr][nc]))continue; if(dB[nr][nc]>dB[r][c]+1){ dB[nr][nc]=dB[r][c]+1; que.push(P(nr,nc)); } } que.pop(); } que.push(P(gr,gc)); dG[gr][gc]=0; while(que.size()){ int r,c; tie(r,c)=que.front(); for(int i=0;i<4;i++){ int nr=r+dir4[i]; int nc=c+dir4[i+1]; if(isWall(maze[nr][nc])||isSpring(maze[nr][nc]))continue; if(dG[nr][nc]>dG[r][c]+1){ dG[nr][nc]=dG[r][c]+1; que.push(P(nr,nc)); } } que.pop(); } vector<P> fs; auto b=[&](P p){return max(0ll,min(INF,dG[p.first][p.second]-dB[p.first][p.second]));}; for(int r=0;r<R;r++) for(int c=0;c<C;c++) if(isFloor(maze[r][c])){ fs.push_back(P(r,c)); } sort(fs.begin(),fs.end(),[&](P p,P q){return b(p)<b(q);}); LL K=0; int B=M; for(int i=0,sz=fs.size();i<sz;i++){ K+=dB[fs[i].first][fs[i].second]; } double res=INF; K-=dB[fs[0].first][fs[0].second]; K+=dG[fs[0].first][fs[0].second]; B--; LL prev=b(fs[0]); for(int i=1,sz=fs.size();i<sz;i++){ LL now=b(fs[i]); if(now!=prev){ double b=1.0-B/(double)M; b=(K/(double)M)/b; if(prev<=b&&b<=now){ res=min(res,b); } } K-=dB[fs[i].first][fs[i].second]; K+=dG[fs[i].first][fs[i].second]; B--; prev=now; } if(prev<INF){ double b=1.0-B/(double)M; b=(K/(double)M)/b; if(prev<=b&&b<=INF){ res=min(res,b); } } cout<<min((double)dG[sr][sc],dB[sr][sc]+res)<<endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < n; i++) #define vi vector<int> #define ll long long #define vl vector<ll> #define vll vector<vl> #define double long double const int INF = 1e9; const int di[] = {0, 1, 0, -1}; const int dj[] = {1, 0, -1, 0}; int w, h; string s[500]; int f[500][500]; int g[500][500]; int si, sj, gi, gj; const double inf = 1e18; void sub(double prob) { using State = pair<int, pair<int, int>>; queue<State> Q; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (s[i][j] == '*') { f[i][j] = 0; g[i][j] = 0; for (int k = 0; k < 4; ++k) { int ni = i + di[k]; int nj = j + dj[k]; Q.push(make_pair(1, make_pair(ni, nj))); } } } } while (!Q.empty()) { auto q = Q.front(); Q.pop(); int c = q.first; int i = q.second.first; int j = q.second.second; if (s[i][j] == '#') continue; if (g[i][j] < INF) continue; g[i][j] = c; for (int k = 0; k < 4; ++k) { int ni = i + di[k]; int nj = j + dj[k]; Q.push(make_pair(c + 1, make_pair(ni, nj))); } } Q.push(make_pair(0, make_pair(gi, gj))); while (!Q.empty()) { auto q = Q.front(); Q.pop(); int c = q.first; int i = q.second.first; int j = q.second.second; if (s[i][j] == '#') continue; if (f[i][j] < INF) continue; f[i][j] = c; for (int k = 0; k < 4; ++k) { int ni = i + di[k]; int nj = j + dj[k]; Q.push(make_pair(c + 1, make_pair(ni, nj))); } } } double get(int i, int j, double prob) { double val = inf; if (f[i][j] < INF) val = min<double>(val, f[i][j]); if (g[i][j] < INF) val = min<double>(val, g[i][j] + prob); return val; } double avg(double prob) { double sum = 0; int cnt = 0; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (s[i][j] == '.' || s[i][j] == 's') { sum += get(i, j, prob); ++cnt; } } } return sum / cnt; } int main() { cin >> w >> h; for (int i = 0; i < h; ++i) { cin >> s[i]; for (int j = 0; j < w; ++j) { if (s[i][j] == 's') { si = i; sj = j; } else if(s[i][j] == 'g') { gi = i; gj = j; } } } double lo = 0; double hi = 1e17; rep(z, 200) { double mid = (lo + hi) / 2; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { f[i][j] = INF; g[i][j] = INF; } } sub(mid); if (avg(mid) < mid) { hi = mid; } else { lo = mid; } } cout << setprecision(16) << fixed << get(si, sj, lo) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; using lint = long long; template<class T = int> using V = vector<T>; template<class T = int> using VV = V< V<T> >; #define double long double int main() { constexpr double inf = 1e100; cin.tie(nullptr); ios::sync_with_stdio(false); int w, h; cin >> w >> h; V<string> s(h); for (auto&& e : s) cin >> e; int si = -1, sj = -1, gi = -1, gj = -1; for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) if (s[i][j] == 'g') { gi = i, gj = j; } else if (s[i][j] == 's') { si = i, sj = j; } VV<> d(h, V<>(w, -1)); d[gi][gj] = 0; queue< pair<int, int> > que; que.emplace(gi, gj); while (not que.empty()) { int i, j; tie(i, j) = que.front(); que.pop(); for (int di = -1; di <= 1; ++di) for (int dj = -1; dj <= 1; ++dj) if (abs(di) + abs(dj) == 1) { int ni = i + di, nj = j + dj; if (s[ni][nj] != 's' and s[ni][nj] != '.') continue; if (d[ni][nj] != -1) continue; d[ni][nj] = d[i][j] + 1; que.emplace(ni, nj); } } VV<> e(h, V<>(w, -1)); for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) if (s[i][j] == '*') { e[i][j] = 0; que.emplace(i, j); } while (not que.empty()) { int i, j; tie(i, j) = que.front(); que.pop(); for (int di = -1; di <= 1; ++di) for (int dj = -1; dj <= 1; ++dj) if (abs(di) + abs(dj) == 1) { int ni = i + di, nj = j + dj; if (s[ni][nj] != 's' and s[ni][nj] != '.') continue; if (e[ni][nj] != -1) continue; e[ni][nj] = e[i][j] + 1; que.emplace(ni, nj); } } double ng = 0, ok = inf; while (true) { double mid = (ng + ok) / 2; double num = 0, den = 0; for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) if (s[i][j] == 's' or s[i][j] == '.') { num += min<double>(d[i][j] == -1 ? inf : d[i][j], (e[i][j] == -1 ? inf : e[i][j]) + mid); den += 1; } (num / den < mid ? ok : ng) = mid; if ((ok - ng) / ok < 1e-10) break; } double res = min<double>(d[si][sj] == -1 ? inf : d[si][sj], (e[si][sj] == -1 ? inf : e[si][sj]) + ok); cout << fixed << setprecision(15) << res << '\n'; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <memory.h> #include <queue> #include <cstdio> #include <cstdlib> #include <map> #include <cmath> using namespace std; #define rep(i, n) for(int i = 0; i< n; i++) #define rep2(i, m, n) for(int i = m; i < n; i++) typedef long long ll; typedef pair<double, int> P; const ll INF = 1LL << 50; const double EPS = 1e-12; int dy[] = {1, 0, -1, 0}; int dx[] = {0, -1, 0, 1}; int W, H; char field[600][600]; ll a[600][600]; ll b[600][600]; void bfs(char start, ll dist[][600]){ queue<int> que; fill(&dist[0][0], &dist[0][0] + 600 * 600, INF); rep(i, H)rep(j, W){ if(field[i][j] == start){ dist[i][j] = 0; que.push(i * W + j); } } while(!que.empty()){ int p = que.front(); que.pop(); int x = p % W; int y = p / W; rep(i, 4){ int y2 = y + dy[i]; int x2 = x + dx[i]; if((field[y2][x2] == '.' || field[y2][x2] == 's') && dist[y2][x2] == INF){ dist[y2][x2] = dist[y][x] + 1; que.push(y2 * W + x2); } } } } int main(){ while(cin >> W >> H){ int sy = 0, sx = 0; rep(i, H)rep(j, W){ cin >> field[i][j]; if(field[i][j] == 's'){ sy = i, sx = j; } } bfs('*', a); bfs('g', b); long double ub = 1e15; long double lb = 0; rep(i, 1000){ long double mb = (ub + lb) / 2; long double sum = 0; int cnt = 0; rep(j, H)rep(k, W){ if(field[j][k] == 's' || field[j][k] == '.'){ cnt++; sum += min((long double)b[j][k], a[j][k] + mb); } } if(mb > sum / cnt) ub = mb; else lb = mb; } cout << fixed << setprecision(15) << min(lb+a[sy][sx],(long double)b[sy][sx])<< endl; } return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<iostream> #include<algorithm> #include<vector> #include<queue> #include<iomanip> using namespace std; typedef long long ll; typedef pair<ll,ll> P; #define chmin(a,b) a=min(a,b) #define chmax(a,b) a=max(a,b) #define rep(i,n) for(int i=0;i<n;i++) #define mod 1000000007 #define mad(a,b) a=(a+b)%mod #define H 510 ll dx[]={0,1,0,-1},dy[]={1,0,-1,0}; ll h,w; char c[H][H]; ll bane[H][H],goal[H][H]; long double f(ll x,ll y,long double k){ return min((long double)goal[x][y],(long double)bane[x][y]+k); } bool solve(long double k){ long double sum=0; ll cnt=0; rep(i,h)rep(j,w)if(c[i][j]=='.'){ sum+=f(i,j,k); cnt++; } sum/=(long double)cnt; //cout<<"solve:"<<sum<<" "<<k<<endl; return sum<=k; } int main(){ cin>>w>>h; ll sx,sy,gx,gy; rep(i,h)rep(j,w){ cin>>c[i][j]; if(c[i][j]=='s')sx=i,sy=j,c[i][j]='.'; if(c[i][j]=='g')gx=i,gy=j; bane[i][j]=goal[i][j]=1e17; } queue<ll> Qx,Qy,Qcost; Qx.push(gx); Qy.push(gy); Qcost.push(0); while(!Qx.empty()){ ll x=Qx.front(),y=Qy.front(),cost=Qcost.front(); Qx.pop(); Qy.pop(); Qcost.pop(); if(goal[x][y]<=cost)continue; goal[x][y]=cost; rep(r,4){ ll xx=x+dx[r],yy=y+dy[r]; if(0<=xx&&xx<h&&0<=yy&&yy<w&&c[xx][yy]=='.'){ Qx.push(xx); Qy.push(yy); Qcost.push(cost+1); } } } rep(i,h)rep(j,w)if(c[i][j]=='*'){ Qx.push(i); Qy.push(j); Qcost.push(0); } while(!Qx.empty()){ ll x=Qx.front(),y=Qy.front(),cost=Qcost.front(); Qx.pop(); Qy.pop(); Qcost.pop(); if(bane[x][y]<=cost)continue; bane[x][y]=cost; rep(r,4){ ll xx=x+dx[r],yy=y+dy[r]; if(0<=xx&&xx<h&&0<=yy&&yy<w&&c[xx][yy]!='#'&&c[xx][yy]!='*'){ Qx.push(xx); Qy.push(yy); Qcost.push(cost+1); } } } /*cout<<"goal"<<endl; rep(i,h){ rep(j,w){ if(goal[i][j]==1e17)cout<<"# "; else cout<<goal[i][j]<<" "; } cout<<endl; } cout<<"bane"<<endl; rep(i,h){ rep(j,w){ if(bane[i][j]==1e17)cout<<"# "; else cout<<bane[i][j]<<" "; } cout<<endl; }*/ long double l=0,r=1e15,mid; rep(d,100){ mid=(l+r)/2.0; if(solve(mid))r=mid; else l=mid; } cout<<fixed<<setprecision(9)<<f(sx,sy,r)<<endl; /*for(double x=0.01;x<=10.0;x+=0.01){ bool res=solve(x); if(res!=(r<x))cout<<"WrongAnswer"<<endl; }*/ }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <string> #include <map> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) struct Point { int x, y, cost; Point() {;} Point(int x, int y, int cost) : x(x), y(y), cost(cost) {;} }; int w, h; char field[600][600]; int springDist[600][600]; int goalDist[600][600]; const int dx[4] = { 1, 0, -1, 0 }; const int dy[4] = { 0, 1, 0, -1 }; int sx, sy; inline bool Movable(int x, int y) { if (x < 0 || x >= w || y < 0 || y >= h) { return false; } if (field[y][x] != '.') { return false; } return true; } void CalcDist() { MEMSET(springDist, -1); MEMSET(goalDist, -1); queue<Point> que; REP(y, h) { REP(x, w) { if (field[y][x] == '*') { REP(dir, 4) { int nx = x + dx[dir]; int ny = y + dy[dir]; if (!Movable(nx, ny)) { continue; } que.push(Point(nx, ny, 1)); } } } } while (!que.empty()) { Point p = que.front(); que.pop(); if (springDist[p.y][p.x] != -1) { continue; } springDist[p.y][p.x] = p.cost; REP(dir, 4) { int nx = p.x + dx[dir]; int ny = p.y + dy[dir]; if (!Movable(nx, ny)) { continue; } que.push(Point(nx, ny, p.cost + 1)); } } REP(y, h) { REP(x, w) { if (field[y][x] == 'g') { que.push(Point(x, y, 0)); } } } while (!que.empty()) { Point p = que.front(); que.pop(); if (goalDist[p.y][p.x] != -1) { continue; } goalDist[p.y][p.x] = p.cost; REP(dir, 4) { int nx = p.x + dx[dir]; int ny = p.y + dy[dir]; if (!Movable(nx, ny)) { continue; } que.push(Point(nx, ny, p.cost + 1)); } } } double ToGoal(int x, int y, double E) { double ret = 1e+100; if (goalDist[y][x] != -1) { ret = min(ret, (double)goalDist[y][x]); } if (springDist[y][x] != -1) { ret = min(ret, springDist[y][x] + E); } //cout << x << " " << y << endl; assert(goalDist[y][x] != -1 || springDist[y][x] != -1); return ret; } //double vs[510 * 510]; double calc(double E) { //double nE = 0.0; int cnt = 0; priority_queue<double> que; REP(y, h) { REP(x, w) { if (field[y][x] != '.') { continue; } //vs[cnt++] = ToGoal(x, y, E); que.push(-ToGoal(x, y, E)); //nE += ToGoal(x, y, E); cnt++; } } //sort(vs, vs + cnt); REP(i, cnt - 1) { //nE += vs[i]; double l = que.top(); que.pop(); double r = que.top(); que.pop(); que.push(l + r); } return -que.top() / cnt; } int main() { while (scanf("%d %d", &w, &h) > 0) { REP(y, h) { scanf("%s", field[y]); REP(x, w) { if (field[y][x] == 's') { sx = x; sy = y; field[y][x] = '.'; } } } CalcDist(); double left = 0.0; double right = 1e+10; if (springDist[sy][sx] != -1) { REP(iter, 90) { double mid = (left + right) / 2.0; if (calc(mid) > mid) { left = mid; } else { right = mid; } } } printf("%.10f\n", ToGoal(sx, sy, left)); } }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-10) #define equals(a,b) (fabs((a)-(b))<EPS) using namespace std; typedef long double ld; const int MAX = 501,IINF = INT_MAX; const ld LDINF = 1e100; int H,W,sx,sy,gx,gy; ld mincost[MAX][MAX][2]; // mincost[][][0] => from start, [1] = > from star char c[MAX][MAX]; bool ban[MAX][MAX]; vector<int> star,plane; int dx[] = {0,1,0,-1}; int dy[] = {1,0,-1,0}; inline bool isValid(int x,int y) { return 0 <= x && x < W && 0 <= y && y < H; } inline void bfs(vector<int> sp,vector<int> Forbidden,int type){ rep(i,H)rep(j,W) mincost[i][j][type] = LDINF, ban[i][j] = false; queue<int> que; rep(i,(int)sp.size()) que.push(sp[i]), mincost[sp[i]/W][sp[i]%W][type] = 0; rep(i,(int)Forbidden.size()) ban[Forbidden[i]/W][Forbidden[i]%W] = true; while(!que.empty()){ int cur = que.front(); que.pop(); rep(i,4){ int nx = cur % W + dx[i], ny = cur / W + dy[i]; if( c[ny][nx] == '#' ) continue; if( ban[ny][nx] ) continue; if( mincost[ny][nx][type] == LDINF ) { mincost[ny][nx][type] = mincost[cur/W][cur%W][type] + 1; que.push(nx+ny*W); } } } } bool check(ld E){ ld T = 0; rep(i,(int)plane.size()){ int x = plane[i] % W, y = plane[i] / W; T += min(mincost[y][x][0],mincost[y][x][1]+E); } ld len = plane.size(); return len * E > T; } int main(){ cin >> W >> H; rep(i,H)rep(j,W){ cin >> c[i][j]; if( c[i][j] == 's' ) sx = j, sy = i, c[i][j] = '.'; if( c[i][j] == 'g' ) gx = j, gy = i; if( c[i][j] == '*' ) star.push_back(j+i*W); if( c[i][j] == '.' ) plane.push_back(j+i*W); } vector<int> sp,forbidden; sp.push_back(gx+gy*W); forbidden = star; forbidden.push_back(gx+gy*W); bfs(sp,forbidden,0); sp = star; forbidden.push_back(gx+gy*W); //forbidden.clear(); bfs(sp,forbidden,1); ld L = 0, R = 1e10, M = 0; rep(i,65){ M = ( L + R ) * (ld)0.5; if( check(M) ) R = M; else L = M; } cout << setiosflags(ios::fixed) << setprecision(20) << min((ld)mincost[sy][sx][0],(ld)mincost[sy][sx][1]+L) << endl; return 0; }
CPP
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the gust blows cannot be judged. So you thought it was best to act to minimize the expected number of moves required to escape the labyrinth. When I picked up an unidentified scroll that had fallen under my feet and read it as a trial, I happened to be able to perceive the entire map of the labyrinth. Furthermore, by drinking the grass that I happened to have, I was able to know the positions of all the traps. Apparently, there are no traps other than dangerous monsters and springs in this labyrinth. This labyrinth is shaped like a rectangle with several types of tiles, for example: .. ## g. # * #. * #. # ...... # * s # *. * # ".":floor. You can walk around freely on this. "#":wall. You can't get inside the wall. "S": Your first position. Below this tile is the floor. "G": Stairs. If you ride on this tile, you have escaped from the labyrinth. "*":Spring. If you ride on this tile, it will be randomly blown onto one of the floors (excluding stairs and spring tiles). The odds of being hit on each floor are all equal. The type of tile is one of these five. You can move one square at a time from the tile you are currently riding to an adjacent tile in either the up, down, left, or right direction. However, you cannot move to Naname. Given a map of the labyrinth, find the expected number of moves required to escape the labyrinth if you take the best strategy. It is not included in the number of movements that is blown by the spring. Input W H c11 c12 ... c1w c21 c22 ... c2w ::: ch1 ch2 ... ccw On the first line of input, the integer W (3 ≤ W ≤ 500) and the integer H (3 ≤ H ≤ 500) are written in this order, separated by blanks. The integer W represents the width of the labyrinth, and the integer H represents the height of the labyrinth. The following H line contains W letters (not blank delimiters) that represent the map of the labyrinth. The format of this part is as in the example given above. Note that "s" and "g" appear exactly once in the data. In addition, one square around the labyrinth is always surrounded by a wall. In addition, in the given labyrinth, no matter how you move and how it is blown by the spring, you will fall into a state where you cannot escape even if you can arbitrarily set the floor to be blown by the spring. You can assume that there is no such thing. Output Output the expected number of moves to escape when you take the best strategy. The output may contain errors, but the relative error to the true value must be less than 10-9. Examples Input 8 6 ######## #..##g.# #*#.*#.# #......# #*s#*.*# ######## Output 5.857142857143 Input 8 6 ..##g.# *#.*#.# ......# *s#*.*# Output 5.857142857143 Input 21 11 *#*.*.*.*.*.*.*.*#*# *#...............#*# *#.#.#.#.#.#.#.#.#*# .#.#.#.#.#.#.#.#.## ...................# .#.#.#.#.#.#.#.#.## s#.#.#.#.#.#.#.#.#g# ...................# ...................# Output 20.000000000000 Input 9 8 ...#*.*# .*.#...# ...#*.*# .s....g# .*#.*..# Output 5.000000000000
7
0
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> l_l; typedef pair<int, int> i_i; #define EPS (1e-7) const long double INF = 1e17; #define PI (acos(-1)) //const ll mod = 1000000007; int W, H; string field[505]; int sh, sw, gh, gw; long double dist[505][505]; struct query { int h, w; long double cost; query(int _h, int _w, long double _cost) { h = _h; w = _w; cost = _cost; } }; bool operator <(query a, query b) { return a.cost < b.cost; } bool operator >(query a, query b) { return a.cost > b.cost; } bool chmin(long double &a, long double b) { if(a > b) { a = b; return true; } return false; } int dh[4] = {1, 0, -1, 0}; int dw[4] = {0, 1, 0, -1}; int main() { //cout.precision(10); cin.tie(0); ios::sync_with_stdio(false); cin >> W >> H; for(int h = 1; h <= H; h++) { cin >> field[h]; field[h] = "#" + field[h]; for(int w = 1; w <= W; w++) { if(field[h][w] == 's') { sh = h; sw = w; } if(field[h][w] == 'g') { gh = h; gw = w; } if(field[h][w] == '.') { } } } long double ok = 1e16; long double ng = 0; priority_queue<query, vector<query>, greater<query>> que; for(int _ = 1; _ <= 100; _++) { long double mid = (ok + ng) / 2.0; for(int h = 1; h <= H; h++) { for(int w = 1; w <= W; w++) { dist[h][w] = INF; if(field[h][w] == '*') { que.emplace(h, w, mid); dist[h][w] = mid; } } } dist[gh][gw] = 0; que.emplace(gh, gw, 0); while(!que.empty()) { query now = que.top(); que.pop(); long double newcost = now.cost + 1.0; for(int k = 0; k < 4; k++) { int newh = now.h + dh[k]; int neww = now.w + dw[k]; if(field[newh][neww] == '#') { continue; } if(field[newh][neww] == '*') { continue; } if(chmin(dist[newh][neww], newcost)) que.emplace(newh, neww, newcost); } } long double distsum = 0.0; long double grids = 0.0; for(int h = 1; h <= H; h++) { for(int w = 1; w <= W; w++) { if(field[h][w] == '#') continue; if(field[h][w] == '*') continue; if(field[h][w] == 'g') continue; if(abs(dist[h][w] - INF) < EPS) continue; grids += 1.0; distsum += dist[h][w]; } } /* cerr << "----" << mid << "----" << endl; for(int h = 1; h <= H; h++) { for(int w = 1; w <= W; w++) cerr << dist[h][w] << " "; cerr << endl; } */ if(distsum / grids < mid) ok = mid; else ng = mid; if(_ == 100) { cout << fixed << setprecision(20) << dist[sh][sw] << endl; return 0; } } return 0; }
CPP