文章目录
题目链接 2018浙江省省赛
A - Peak
题意
判断这个序列是否为山峰型的,即先增加后减少
分析
先统计增加的,再统计减少的
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
int a[maxn];
int main(){
int T;
scanf("%d", &T);
while(T--) {
int n;
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
int pos = 1;
while(pos+1 <= n && a[pos+1] > a[pos]) pos++;
if(pos == 1 || pos == n) {
puts("No");
}else{
pos++;
while(pos <= n && a[pos] < a[pos-1]) pos++;
puts(pos == n+1 ? "Yes" : "No");
}
}
return 0;
}
B - King of Karaoke
题意
给一个序列 D D D,可以对每一个 D i D_i Di 加上一个值 k k k
问最后可以使序列 D D D 和序列 S S S 最多有多少个相同的元素
分析
直接用 map 统计 D i − S i D_i - S_i Di−Si 的值,取个数最多的
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 5;
unordered_map<int, int> mp;
int a[maxn];
int b[maxn];
int main(){
int T;
scanf("%d", &T);
while(T--) {
int n; mp.clear();
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
for(int i = 1, x; i <= n; ++i) {
scanf("%d", &x);
mp[x - a[i]]++;
}
int ans = 1;
for(auto i : mp)
ans = max(ans, i.second);
printf("%d\n", ans);
}
return 0;
}
C -
题意
分析
代码
D - Sequence Swapping [dp] ★★★
题意
给一个串仅包含 (, ),每个括号有一个权值(权值是跟着括号的),当且仅当 s [ k ] = ′ ( ′ , s [ k + 1 ] = ′ ) ′ s[k]='(', s[k+1]=')' s[k]=′(′,s[k+1]=′)′ 的时候,才可以交换这两个括号
交换括号可以得到的价值为这两个括号的权值的乘积
可以交换任意次数,问可以得到价值总和最大为多少
分析
参考博客
逆向遍历,可以交换的情况为右括号在右边,左括号在左边
d p [ n u m ] [ j ] dp[num][j] dp[num][j] 记录右边 第 n u m num num个左括号,与右边 j − n u m j-num j−num 个右括号都进行交换后得到的价值
上面这个是选择交换的情况
如果不选择交换,直接从右括号个数+1的位置得到值
详见代码
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e3+5;
char s[maxn];
int cnt[maxn]; // 右边的右括号个数
ll sum[maxn]; // sum[cnt[i]] 右边cnt[i]个括号的权值和
ll dp[2][maxn]; // i位置的左括号匹配后右边为j个右括号的最大值
ll a[maxn];
inline void init() {
memset(dp, 0, sizeof(dp));
memset(sum, 0, sizeof(sum));
memset(cnt, 0, sizeof(cnt));
}
int main(){
int T;
scanf("%d", &T);
while(T--) {
int n; init();
scanf("%d%s", &n, s+1);
for(int i = 1; i <= n; ++i) scanf("%lld", &a[i]);
for(int i = n; i >= 1; --i)
cnt[i] = cnt[i+1] + (s[i] == ')' ? 1 : 0);
for(int i = n; i >= 1; --i) {
if(cnt[i] != cnt[i+1])
sum[cnt[i]] = sum[cnt[i]-1] + a[i];
}
ll ans = 0; int k1 = 0;
for(int i = n; i >= 1; --i) {
if(s[i] == ')') continue;
int k2 = k1^1; // 当前为 ( 可以交换
for(int j = i+cnt[i]; j >= i; --j) {
// i+右括号个数,计算与右括号交换得到的初始值
// i位置的左括号与 i->(j-i)个右括号交换
ll x = a[i] * (sum[cnt[i]]-sum[cnt[i]-(j-i)]);
dp[k1][j] = dp[k2][j+1] + x; // 从右括号个数多一个的位置转移过来
ans = max(ans, dp[k1][j]);
}
for(int j = i+cnt[i]-1; j >= 1; --j) {
// dp[i][j+1]不进行交换
dp[k1][j] = max(dp[k1][j], dp[k1][j+1]);
ans = max(ans, dp[k1][j]);
}
k1 ^= 1;
}
printf("%lld\n", ans)