2B - The least round way
2013-10-14 21:53 BrokenJar 阅读(143) 评论(0) 编辑 收藏 举报#include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; int n; vector< vector< vector<int> > > coll; vector< string > best_way(2); int zero_x = 0; /* struct elem{ int factor_count_2; int factor_count_5; int orign_2; int orign_5; } */ int get_factor_count(int number, int factor) { int result = 0; while(number && !(number%factor)) { number/=factor; ++result; } return result; } void find_best_way(const int& x) { for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(i > 0 && j > 0) { int l = coll[i-1][j][x]; int t = coll[i][j-1][x]; if(l < t) { coll[i][j][x] += l; coll[i][j][x+2] = 'U'; } else { coll[i][j][x] += t; coll[i][j][x+2] = 'L'; } } else if(i == 0 && j > 0) { coll[i][j][x] += coll[i][j-1][x]; coll[i][j][x+2] = 'L'; } else if(j == 0 && i > 0) { coll[i][j][x] += coll[i-1][j][x]; coll[i][j][x+2] = 'U'; } } } } string get_way(const int& x) { string result; int i = n - 1, j = n - 1; while(i > 0 || j > 0) { int origin = coll[i][j][x+2]; if(origin == 'L'){ result.push_back('R'); --j; } else if(origin = 'U'){ result.push_back('D'); --i; } } reverse(result.begin(), result.end()); return result; } string get_way_include_zero() { string result; int i, limit = coll.size(); for(i = 1; i < zero_x; ++i) result.push_back('R'); for(i = 1; i < limit; ++i) result.push_back('D'); for(i = zero_x; i < limit; ++i) result.push_back('R'); return result; } int main() { cin >> n; coll.resize(n); for(int i = 0; i < n; ++i) { coll[i].resize(n); for(int j = 0; j < n; ++j) { coll[i][j].resize(4); int number; cin >> number; if(number == 0 && !zero_x) zero_x = j+1; coll[i][j][0] = get_factor_count(number, 2); coll[i][j][1] = get_factor_count(number, 5); } } find_best_way(0); find_best_way(1); const vector<int> end = coll.back().back(); int min_count_2 = end[0], min_count_5 = end[1]; if(zero_x && min_count_2 > 1 && min_count_5 > 1) { cout << '1' << endl; cout << get_way_include_zero() << endl; } else if(min_count_2 < min_count_5) { cout << min_count_2 << endl; cout << get_way(0) << endl; } else { cout << min_count_5 << endl; cout << get_way(1) << endl; } }