Codeforces Round #632 (Div. 2)補題
C
題目
題目大意
給一串數列,問能選出多少個好數組
好數組的定義是,任一子數組的和不爲0
思路
1.先算出前綴和,只要前綴和相同的就說明該區間和等於0
2.記錄一下數組i能往前拓展好數組的最前位置,就是前綴和相同的位置
3.tip:如何記錄子區間數目?
對於每一個數,我們設a[i]是一個以這個數爲端點的子區間數,那麼很容易就得到a[i] = i,所以長度爲n的子區間數就是1加到n
代碼
#include <iostream>
#include <cstdio>
#include <set>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <unordered_map>
using namespace std;
#define dbg(x) cerr << #x " = " << x << endl;
typedef pair<int, int> P;
typedef long long ll;
const int MAXN = 2e5+5;
ll sum[MAXN];
ll a[MAXN];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll n;
cin >> n;
map<ll, ll> m;
for(ll i = 1; i <= n; i++)
{
cin >> a[i];
sum[i] = sum[i-1] + a[i];
}
ll ans = 0;
m[0] = 0;
ll MAX = -0x3f3f3f3f;
for(ll i = 1; i <= n; i++)
{
MAX = max(MAX, (m.find(sum[i]) == m.end()) ? 0 : (ll)m[sum[i]] + 1);
m[sum[i]] = i;
ans += i - MAX;
}
cout << ans << endl;
}
D
題目
題目大意
一列人,如果面向對方就要轉向,一個人一秒只能轉一次,一秒可以有多個人轉,問能否在k秒鐘恰好轉完
思路
記錄每一秒最多轉多少個,記錄下來,就可以知道最快要多少秒轉完,也知道最慢多少秒,如果k處於最快和最慢之間,可以把一秒鐘轉多個人改成多秒鐘轉一個人,可以把答案湊出k
代碼
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> ans;
int a[3050];
char c;
int main()
{
int n, k, sum = 0;
cin >> n >> k;
for (int i = 1; i <= n; i++)
{
cin >> c;
a[i] = (c == 'R');
}
while (1)
{
vector<int> now;
for (int i = 1; i < n; i++)
if (a[i] && !a[i + 1])
now.push_back(i), swap(a[i], a[i + 1]), i++;
if (now.empty())
break;
sum += now.size();
ans.push_back(now);
}
if (ans.size() > k || sum < k)
puts("-1");
else
{
int re = k - ans.size();
for (auto now : ans)
{
while (now.size() > 1 && re > 0)
{
printf("1 %d\n", now.back());
now.pop_back();
re--;
}
printf("%d ", now.size());
for (auto i : now)
printf("%d ", i);
puts("");
}
}
}