1 solutions
-
0
题目解析
首先将所有能配对的字母配对,假设配成了 对,然后剩下 个单独的字符(即出现次数为奇数的字符)。
如果 ,那么最优方案一定是将所有的字母拼成一个回文串,答案为 (即所有配对的总长度)。
否则拼成 个串,然后将这 对字符均匀分配给这 个串,每个串的长度为 。
核心思路:
- 统计每种字母出现次数,将偶数部分(除以 2)累计到
sum中,同时统计有多少个出现次数为奇数的字母,记为od。 - 如果
od = 0,说明全部都是偶数次,可以拼成一个完整的回文串,答案为sum * 2。 - 如果
od > 0,则拼成od个回文串,将sum对字母均匀分配到od个串中,每个串长度为sum / od * 2 + 1。
时间复杂度:。
参考代码
#include <bits/stdc++.h> #define rep(i, a, b) for (int i = (a); i <= (b); ++i) #define dep(i, a, b) for (int i = (a); i >= (b); --i) using namespace std; typedef long long ll; const int N = 2e5 + 20; inline int read() { char c = getchar(); int x = 0, f = 1; while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); } return x * f; } int q[N]; int n; int main() { int T = read(); while (T--) { n = read(); int sum = 0; int od = 0; rep(i, 1, n) { q[i] = read(); if (q[i] & 1) { od++; sum += q[i] / 2; } else sum += q[i] / 2; } if (!od) printf("%d\n", sum * 2); else printf("%d\n", sum / od * 2 + 1); } return 0; } - 统计每种字母出现次数,将偶数部分(除以 2)累计到
- 1
Information
- ID
- 190
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- 9
- Tags
- (None)
- # Submissions
- 7
- Accepted
- 7
- Uploaded By