Codeforces Round #775 (Div. 2)部分题解
本篇题解只是记录我的做题过程代码,不提供最优解 (另外这里所有的时间复杂度都只分析单个样例,不算 t t t的时间复杂度)
A
. 本题设计算法:模拟
时间复杂度 O ( n ) O(n) O(n)
#include <iostream> #include <cstring> #include <algorithm> #include <vector> #include <map> using namespace std; typedef long long ll; const int N = 2e5 + 10,INF = 1e9; int a[N]; map<int,int> st; void solve() { int n; cin >> n; for (int i = 1;i <= n;i ++ ) cin >> a[i]; int x = 1,first = -1,second = -1; for (int i = 1;i <= n;i ++ ) { if (a[i] == 0 && first == -1) { first = i; for (int j = i;j <= n;j ++ ) { if (a[j] == 1) { i = j - 1; break; }else x ++; } } else if (a[i] == 0 && first != -1) { second = i; break; } //cout << i << << x << ; } int index = -1; for (int i = n;i >= 1;i -- ) { if (a[i] == 0 ) { index = i; break; } } if (first == -1) cout << 0 << ; else if (second == -1) cout << x << ; else cout << index - first + 2 << ; } int main() { int t; cin >> t; while (t -- ) { solve(); } return 0; }
B
. 本题设计算法:贪心 贪心策略:只要找到传球数最大的球员与剩余的球员对比即可
时间复杂度 O ( n ) O(n) O(n)
#include <iostream> #include <cstring> #include <algorithm> #include <vector> #include <map> using namespace std; typedef long long ll; const ll N = 2e5 + 10,INF = 1e9 + 7; ll a[N]; void solve() { ll n,maxn = -INF; cin >> n; ll sum = 0; for (int i = 1;i <= n;i ++ ) { cin >> a[i]; maxn = max(maxn,a[i]); sum += a[i]; } ll yu = sum - maxn; if (maxn == 0) cout << 0 << ; else if (maxn <= yu) cout << 1 << ; else { yu ++; ll res = maxn - yu; cout << res + 1 << ; } } int main() { int t; cin >> t; while (t -- ) { solve(); } return 0; }
C
. **本题设计算法:关键字排序 + 快速组合 **
先分别对每种颜色的所有可能坐标进行统计
然后枚举所有颜色,求曼哈顿距离的和【注意对x与y坐标排序(这样可以忽略曼哈顿距离的绝对值,从而比较好求),这里分开x,y坐标求比较好】
另外注意,同颜色求和是要找到 C l e n 2 C_{len}^2 Clen2组合相减的规律,用O(n)的时间求出,而不是暴力求,会超时。
举个栗子: 1 2 3 4 的 C 4 2 C_4^2 C42的组合相减
时间复杂度 O ( n 2 ∗ l o g n ) O(n^2 * logn) O(n2∗logn)
#include <iostream> #include <algorithm> #include <cstring> #include <vector> using namespace std; const int N = 2e5 + 10; typedef long long ll; typedef pair<ll,ll> PII; vector<PII> ver[N]; ll res,d; bool cmp(PII x,PII y) { return x.second < y.second; } int main() { ll n,m; cin >> n >> m; for (ll i = 1;i <= n;i ++ ) { for (ll j = 1;j <= m;j ++ ) { ll val; cin >> val; ver[val].push_back({i,j}); } } for (ll i = 1;i <= N;i ++ ) { ll len = (ll)ver[i].size(); if (len <= 1) continue; sort (ver[i].begin(),ver[i].end()); for (ll j = 1;j < len;j ++ ) res += (len - j) * j * (ver[i][j].first - ver[i][j - 1].first);//优化重点 sort (ver[i].begin(),ver[i].end(),cmp); for (ll j = 1;j < len;j ++ ) res += (len - j) * j * (ver[i][j].second - ver[i][j - 1].second);//优化重点 } cout << res << ; return 0; }
下一篇:
图解希尔排序---C实现