Codeforces Round #FF (Div. 2) 题解
链接:http://codeforces.com/contest/447
题意:找出hash时第一次产生冲突的位置。
解题思路:用一个数组表示是否存放有hash之后的元素,0表示这个位置还没有使用过。1表示这个位置上有hash之后的元素(即产生了冲突)。
代码:
#include <cstdio>
#include <cstring>
const int MAXN = 305;
int a[MAXN], p, n, ans = -1;
int main()
{
bool flag = true;
scanf("%d%d", &p, &n);
for(int i = 0; i < n; i++)
{
int x;
scanf("%d", &x);
if(flag)
{
if(0 == a[x % p])
{
a[x % p] = 1;
}
else
{
ans = i + 1;
flag = false;
}
}
}
printf("%d\n", ans);
return 0;
}
链接:http://codeforces.com/contest/447/problem/B
题意:在给出的字符串中添加k个字符,求能够得到的最大权值和。
解题思路:找出最大的位权,将k个有最大位权的字符放到原字符串的末尾。求权值和。ps:答案可能会超出int。要用long long
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
int k, a[27], imax = -1;
cin >> s >> k;
for(int i = 0; i < 26; i++)
{
cin >> a[i];
if(a[i] > imax)
{
imax = a[i];
}
}
long long ans = 0;
int len = s.length();
for(int i = 0; i < len; i++)
{
ans += a[s[i] - 'a'] * (i + 1);
}
ans += (long long)imax * k * (2 * len + k + 1) / 2;
cout << ans << endl;
}
DZY has a sequence a, consisting of n integers.
We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.
Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).
In a single line print the answer to the problem — the maximum length of the required subsegment.
6 7 2 3 1 5 6
5
You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
题意:从一串数字中选出一个子串。能够改变子串中一个数字的值得到一个新的子串,求最大的递增新子串的长度。
解题思路:
将原数组切割成递增的子串,记录下每一个子串的開始和结束位置,以及长度。
接下来要分几种情况讨论:1.相邻的两个子串改变一个数字之后,能够合并形成新的递增子串。2.相邻的3个子串,中间子串长度为1。改变中间的数字后能够形成新的递增子串,3.相邻的子串不能合并形成新的递增子串,可是能够在原串的基础上。得到一个长度添加1的新的递增子串(在子串开头位置前有数字。或是结束位置后有数字)。
代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 100010; int a[MAXN]; struct P { int l, len, r; }; P p[MAXN]; int n; int main() { memset(p, 0, sizeof(p)); scanf("%d", &n); int t = 0; for(int i = 0; i < n; i++) { scanf("%d", &a[i]); if(!i) { p[t].len++; p[t].l = p[t].r = i; continue; } if(a[i] <= a[i - 1]) { t++; } if(0 == p[t].len) { p[t].l = i; } p[t].len++; p[t].r = i; } int ans = p[0].len < n ?
p[0].len + 1 : p[0].len; for(int i = 1; i <= t; i++) { ans = max(ans, p[i].len + 1); if(a[p[i].l] > a[p[i - 1].r - 1] + 1 || a[p[i].l + 1] > a[p[i - 1].r] + 1) { ans = max(ans, p[i].len + p[i - 1].len); } if(i >= 2 && 1 == p[i - 1].len && a[p[i].l] > a[p[i - 2].r + 1]) { ans = max(ans, p[i].len + p[i - 2].len + 1); } // printf("%d \n", p[i].len); } printf("%d\n", ans); return 0; }