http://codeforces.com/contest/1307

C. Cow and Message

 

题意:给一个串S,其中有等差数列位置的子序列为密码,问等差数列位置出现最多的序列是什么,只要给出最多的出现次数。

如果一个大于2位的序列出现多次,一定有长度为2的序列出现次数只多不少,所以出现次数最多的一定是长度为2的序列,或者长度为1的序列。

只有26个字母,两位串,直接枚举就好了,遍历每一位同时更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 10;
char s[N];
ll cnt[100][100], b[100];
ll ans;
int main() {
scanf("%s", s);
for (int i = 0; s[i]; i++) {
int c = s[i] - 'a';
for (int j = 0; j < 26; j++) {
cnt[j][c] += b[j];
ans = max(ans, cnt[j][c]);
}
b[c]++;
ans = max(ans, b[c]);
}
cout << ans << endl;
return 0;
}

 

D. Cow and Fields

 

题意:有n个点的无向连通图,其中有k个红点,现在要找两个红点连一条无向边,使得从1到n的最短路最长。

先处理出以1和n为源点的最短路,新的最短路如果经过新加的边,最短路一定是1到第一个红点的最短路+1+第二个红点到n的最短路。而如果不经过新边,那就是原来的最短路。

所以假设经过新边,那就要找到最大的 d1[u]+1+d2[v]d1[u]+1+d2[v],那就枚举第一个红点,从它向后面的第一个红点连边,再找到所有连边情况的最大值。

注意一定要向后面的红点连边,否则就不是最短路了。而什么叫后面,就是距离n刚好比这个红点近一点。因为是贪心地连边,所以一定不能找错。

而一旦找到一种方式长度大于原最短路,就连这条边,答案就一定是原最短路了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
int n, m, k;
int red[N];
vector<int>G[N];
int d1[N], d2[N];
void bfs(int s, int* d) {
fill(d, d + n + 1, -1);
queue<int>que;
que.push(s);
d[s] = 0;
while (!que.empty()) {
int u = que.front(); que.pop();
for (int v : G[u]) {
if (d[v] == -1) {
d[v] = d[u] + 1;
que.push(v);
}
}
}
}
vector<int>vc2;
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < k; i++) {
scanf("%d", &red[i]);
}
for (int i = 0; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
bfs(1, d1);
bfs(n, d2);
for (int i = 0; i < k; i++) {
vc2.push_back(d2[red[i]]);
}
sort(vc2.begin(), vc2.end());
int tmp = d1[n], ans = -1;
for (int i = 0; i < k; i++) {
auto pos = upper_bound(vc2.begin(), vc2.end(), d2[red[i]]);
--pos;
if (pos == vc2.begin())continue;
--pos;
if ((*pos) + d1[red[i]] + 1 >= tmp) { ans = tmp; break; }
ans = max(ans, (*pos) + d1[red[i]] + 1);
}
printf("%d\n", ans);
return 0;
}