天津大学 2025 预推免 第二批 机试 题解
1
求各位数字平方和。
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{int t;cin >> t;while(t--){ll ans = 0;int x;cin >> x;while(x){int d = x % 10;ans += 1ll * d * d;x /= 10;}cout << ans << '\n';}
}
2
根据y+m+d、y、m、d的优先级,从小到大排序日期。
#include <bits/stdc++.h>
using namespace std;
struct Info
{int s;int y, m, d;bool operator < (const Info& t) const{if(s != t.s) return s < t.s;if(y != t.y) return y < t.y;if(m != t.m) return m < t.m;return d < t.d;}
};
vector<Info> v;
int main()
{int n;cin >> n;for(int i = 1; i <= n; i++){string s;cin >> s;int sz = s.size();vector<int> vi;for(int j = 0; j < sz; j++){if(s[j] == '.') continue;int k = j+1;while(k < sz && s[k] != '.') k++;string sx = s.substr(j, k-j);int x = stoi(sx);vi.push_back(x);j = k;}v.push_back({vi[0]+vi[1]+vi[2],vi[0],vi[1],vi[2]});}sort(v.begin(), v.end());for(int i = 0; i < n; i++){printf("%d.%d.%d\n",v[i].y,v[i].m,v[i].d);}
}
3
计算两个圆的几何关系。
#include <bits/stdc++.h>
using namespace std;
using db = double;
const db eps = 1e-6;
int main()
{int t;cin >> t;while(t--){db a1, b1, r1, a2, b2, r2;cin >> a1 >> b1 >> r1 >> a2 >> b2 >> r2;db d = sqrt((a1 - a2) * (a1 - a2) + (b1 - b2) * (b1 - b2));db mx = r1 + r2;db mn = fabs(r1 - r2);int ans;if(d - mx > eps) ans = 0;else if(fabs(d - mx) < eps || fabs(d - mn) < eps) ans = 1;else if(mx - d > eps) ans = 2;else if(mn - d > eps) ans = 3;cout << ans << endl;}
}
4
背包问题。体积也是权重。
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
const int M = 1e4+10;int f[N][M];
int a[N];int main()
{int n, m;cin >> n >> m;for(int i = 1; i <= n; i++) cin >> a[i];for(int i = 1; i <= n; i++)for(int j = 1; j <= m; j++){f[i][j] = f[i-1][j];if(j >= a[i]) f[i][j] = max(f[i][j], f[i-1][j-a[i]] + a[i]);}cout << f[n][m];
}
5
带通配符的括号匹配问题。需要是的字符串数目最少+字典序最小。
#include <bits/stdc++.h>
using namespace std;
using pic = pair<int, char>;
int main()
{ int n;cin >> n;while(n--){stack<int> L, R, S;string s;cin >> s;int sz = s.size();for(int i = 0; i < sz; i++){char c = s[i];if(c == '(') L.push(i);else if(c == ')') R.push(i);else if(c == '*') S.push(i);}vector<pic> v;while(L.size() || R.size()){if(L.size() && R.size()) //都有{int l = L.top(), r = R.top();if(l < r) {L.pop(); R.pop(); v.push_back({l, '('}); v.push_back({r, ')'});}else{while(S.size() && S.top() < L.top()) S.pop();if(S.size() && S.top() > l) {int s = S.top(); S.pop(); L.pop(); v.push_back({l, '('}); v.push_back({s, ')'});}else break;}}else if(L.size()) //左有{int l = L.top();while(S.size() && S.top() < L.top()) S.pop();if(S.size() && S.top() > L.top()) {int s = S.top(); S.pop(); L.pop(); v.push_back({l, '('}); v.push_back({s, ')'});}else break;}else if(R.size()) //右有{int r = R.top();while(S.size() && R.top() < S.top()) S.pop();if(S.size() && R.top() > S.top()) {int s = S.top(); S.pop(); R.pop(); v.push_back({s, '('}); v.push_back({r, ')'});}else break;}}if(!L.size() && !R.size()){sort(v.begin(), v.end());for(auto u : v) cout << u.second;puts("");}else puts("No solution!");}
}