1.编译器求大小问题
#include<iostream> #include<vector> #include<algorithm> #include <cassert> #include<sstream> #include <stack> using namespace std; bool check(string& str) { for (char c : str) { if (c == '[') return true; } return false; } int main() { string s; getline(cin, s); stringstream ss(s); string temp; int cnt = 0; int mod = 1; int z = 0; while (getline(ss, temp, ' ')) { if (mod) { if (temp == "int") z = 4; else if (temp == "char") z = 1; else if (temp == "long") z = 8; mod = 0; continue; } stringstream ss2(temp); string temp2; while (getline(ss2, temp2, ',')) { if (check(temp2)) { stack<char> st; vector<int> vec; int i, j; int num = 1, n = temp2.size(); for (int k = 0; k < n; k++) { if (temp2[k] == '[') { i = k + 1; } else if (temp2[k] == ']') { j = k - 1; string str = temp2.substr(i, j - i + 1); vec.push_back(atoi(str.c_str())); } } for (int x : vec) num *= x; cnt += num * z; } else { cnt += z; } } } cout << cnt << endl; }
2.联盟问题,并查集解法
#include<iostream> #include<vector> #include<algorithm> #include <cassert> #include<sstream> #include <stack> #include<unordered_map> using namespace std; unordered_map<int, int> mp; vector<int> vec; int find(vector<int>& dp, int x) { while (dp[x] != x) { x = dp[x]; } return dp[x]; } bool check(vector<int>& dp, int a, int b) { int x = find(dp, a); int y = find(dp, b); if (x == y) return true; else return false; } int func(vector<int>& dp, int a, int b) { int x = find(dp, a); int y = find(dp, b); if (x == y) return -1; else { int num = (x + y) ^ (abs(vec[x] - vec[y])); if (x < y) { dp[y] = x; vec[x] = vec[x] + vec[y]; } else { dp[x] = y; vec[y] = vec[x] + vec[y]; } return num; } } int main() { int n, m; cin >> n >> m; int cnt = n; vec = vector<int>(n + 1); vector<int> dp(n + 1); for (int i = 0; i < n + 1; i++) dp[i] = i; int id = 1; int x; while (cnt--) { cin >> x; vec[id++] = x; } cnt = m; int a, b, t, q; while (cnt--) { cin >> t >> a >> b; if (t == 1) { q = func(dp, a, b); if (q != -1) cout << q << endl; } else { if (check(dp, a, b)) cout << "YES" << endl; else cout << "NO" << endl; } } return 0; }
全部评论
(1) 回帖