第一题,移位
#include <iostream> #include <vector> using namespace std; void solution(vector<unsigned int>& nums){ for(auto& n : nums){ for(int i=0; i<16; ++i){ bool bits0 = (0x1 << (2*i)) & n; bool bits1 = (0x1 << (2*i+1)) & n; if(bits0 != bits1){ n ^= (0x1 << (2*i)); n ^= (0x1 << (2*i+1)); } } } unsigned int lowBits = (nums[0] & 0x3); nums[0] >>= 2; for(int i=1; i<nums.size(); ++i){ unsigned int tmp = (nums[i] & 0x3); nums[i] >>= 2; nums[i] += (lowBits << 30); lowBits = tmp; } nums[0] += (lowBits << 30); } int main(){ unsigned int n; vector<unsigned int> nums; while(cin >> n){ nums.push_back(n); } solution(nums); int fg = false; for(auto i : nums){ if(fg) cout << " "; fg = true; cout << i; } cout << endl; } // 1 2 1073741824 2147483648第二题,最大面积
#include <iostream> #include <vector> #include <sstream> using namespace std; int solution(vector<int>& width, vector<int>& height){ if(width.empty() || height.empty() || width.size() != height.size()){ return 0; } int ans = 0; for(int i=0; i<width.size(); ++i){ if(width[i] <1 || width[i] > 100 || height[i] <1 || height[i] > 100){ return 0; } int sum = width[i] * height[i]; for(int k = i-1; k>=0 && height[k] >= height[i]; --k){ sum += width[k] * height[i]; } for(int k = i+1; k<width.size() && height[k] >= height[i]; ++k){ sum += width[k] * height[i]; } ans = max(ans, sum); } return ans; } int main(){ string sw, sh; getline(cin, sw, ']'); getline(cin, sh, ']'); vector<int> width, height; istringstream issw(sw.substr(1)); istringstream issh(sh.substr(2)); string n; while(getline(issw, n, ',')){ width.push_back(stoi(n)); } while(getline(issh, n, ',')){ height.push_back(stoi(n)); } cout << solution(width, height) << endl; return 0; } // [1,1,1,1,2,1,1],[5,2,5,4,5,1,6]
第三题, 暴力回溯,过了0.7
#include <iostream> #include <vector> #include <string> #include <set> using namespace std; int length; vector<char> alpha; vector<string> strs; vector<pair<int, int>> nums; bool helper(string& str){ for(int i=0; i<strs.size(); ++i){ int a = 0, b = 0; string& s = strs[i]; for(int k=0; k<str.size(); ++k){ if(s[k] == str[k]){ ++ a; }else if(str.find(s[k]) != string::npos){ ++ b; } } if(a != nums[i].first || b != nums[i].second){ return false; } } return true; } bool backTrack(string& ans){ if(ans.size() >= length){ if(helper(ans)) return true; return false; } for(int i=0; i<alpha.size(); ++i){ if(alpha[i] == '#') continue; ans.push_back(alpha[i]); char t = alpha[i]; alpha[i] = '#'; if(backTrack(ans)) return true; ans.pop_back(); alpha[i] = t; } return false; } int main(){ int cnt; set<char> st; // 只保存预言中出现过的字母,从中选择做回溯,避免使用全部26个字母 cin >> length >> cnt; while(cnt--){ string s; int a, b; cin >> s >> a >> b; strs.push_back(s); nums.push_back({a, b}); for(char c : s){ st.insert(c); } } for(char c : st){ alpha.push_back(c); } string ans; backTrack(ans); cout << ans << endl; return 0; }
全部评论
(6) 回帖