腾讯笔试 8.23 后台&综合 AC 4
1. 链表
用cin会超时,改成scanf过了
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
scanf("%d%d", &n, &k);
int val;
for (int i = 1; i <= n; ++i) {
scanf("%d", &val);
if (i == k) continue;
printf("%d ", val);
}
cout << endl;
}
2.第k个子串
k<=5暴力就行 O(n)
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
int k;
cin >> s;
cin >> k;
set<string> se;
int n = s.size();
for (int i = 0; i < n; ++i) {
for (int j = 1; j < 6; ++j) {
if (i + j - 1 < n) {
se.insert(s.substr(i, j));
if (se.size() > 5) se.erase(*se.rbegin());
}
}
}
vector<string> res;
for (auto i : se) res.push_back(i);
cout << res[k - 1] << endl;
}
3. 拆数字
其中一个数字为n的最高为减一,其他位为9
如 :
24 = 19 + 6
144 = 99 + 45
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int s(LL n) {
int res = 0;
while (n) {
res += n % 10;
n /= 10;
}
return res;
}
int main() {
int T;
cin >> T;
while (T--) {
LL n;
cin >> n;
if (n < 10) {
cout << n << endl;
continue;
}
LL t = n;
int digit = 0;
while (t > 10) {
t /= 10;
digit++;
}
while (digit) {
t *= 10;
digit--;
}
int res = s(t - 1) + s(n - t + 1);
cout << res << endl;
}
}
4. 刷木板(代码不对,过了35%)
没AC
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5010;
int a[maxn];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
int res = a[0];
for (int i = 1; i < n; ++i) {
res += max(a[i] - a[i - 1] , 0);
}
res = min(res, n);
cout << res << endl;
}
5. 查询子串回文串个数
区间dp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int a[maxn][2];
int dp[405][405];
int inf = 0x3f3f3f3f;
int main() {
string s;
cin >> s;
int t;
scanf("%d", &t);
for (int i = 0; i < t; ++i) {
cin >> a[i][0] >> a[i][1];
}
int n = s.size();
memset(dp, 0x3f, sizeof(dp));
for (int i = 1; i <= n; ++i) {
dp[i][i] = 1;
if (i < n) {
dp[i][i + 1] = s[i - 1] == s[i] ? 1 : 2;
}
}
for (int len = 3; len <= n; ++len) {
for (int l = 1; l + len - 1 <= n; ++l) {
int r = l + len - 1;
if (s[l - 1] == s[r - 1] && dp[l + 1][r - 1] == 1) {
dp[l][r] = 1;
continue;
}
for (int k = l; k < r; ++k) {
dp[l][r] = min(dp[l][r], dp[l][k] + dp[k + 1][r]);
}
}
}
for (int i = 0; i < t; ++i) {
int l = a[i][0], r = a[i][1];
cout << dp[l][r] << endl;
}
}
查看12道真题和解析