A - Even Substrings CodeForces - 1139A
题意:找偶数子串个数。
分析:如果i-th位置为奇数则以它为末尾的子串都为奇数子串减去i即可。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 65010;
int n;
long long num;
char ch[maxn];
int main()
{
scanf("%d", &n);
scanf("%s", ch + 1);
num = (long long) n * (n + 1) / 2;
for(int i = 1; i <= n; i++)
{
if((ch[i] - '0') % 2) num -= i;
}
printf("%lld", num);
return 0;
}
B - Chocolates CodeForces - 1139B
题意:贪心,前面的数一定比后面的数小。然后只需要记录他的后面的最大值,然后前一个数不超过他即可。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 100;
int n;
long long a[maxn];
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%lld", &a[i]);
long long maxx = a[n] + 1, num = 0;
for(int i = n; i >= 1; i--)
{
int re = min(maxx - 1, a[i]);
if(re < 0) re = 0;
num += re;
maxx = re;
}
printf("%lld\n", num);
return 0;
}
C - Edgy Trees CodeForces - 1139C (联通块)
题意:按顺序走最短路,然后必须经过一条黑边,我们只需要将红边单独挑出来求联通快即可。而路径的数目即n^k.
两种方法:
1.并查集,联通点fa[i] == i;
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e6 + 100;
const int mod = 1e9 + 7;
ll n, k, fa[maxn], sa[maxn], ans;
ll pow_fast(ll x, ll n)
{
ll res = 1;
while(n > 0)
{
if(n & 1) res = res * x % mod;
x = x * x % mod;
n >>= 1;
}
return res;
}
ll tofind(ll x)
{
if(x == fa[x])
return x;
return fa[x] = tofind(fa[x]);
}
int main()
{
scanf("%lld%lld", &n, &k);
for(int i = 0; i <= n; i++) fa[i] = i, sa[i] = 1;
for(int i = 1; i < n; i++)
{
ll a, b, c;
scanf("%lld%lld%lld", &a, &b, &c);
if(!c)
{
ll x = tofind(a), y = tofind(b);
fa[x] = y; sa[y] += sa[x];
}
}
ans = pow_fast(n, k);
for(int i = 1; i <= n; i++)
{
if(fa[i] == i)
{
ans = (ans - pow_fast(sa[i], k) + mod) % mod;
}
}
printf("%lld\n", ans);
return 0;
}
2.dfs求联通块。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e6 + 100;
const int mod = 1e9 + 7;
ll n, k, vis[maxn];
ll ans;
vector <long long> vec[maxn];
ll pow_fast(ll x, ll n)
{
ll res = 1;
while(n > 0)
{
if(n & 1) res = res * x % mod;
x = x * x % mod;
n >>= 1;
}
return res;
}
void dfs(ll re, ll &num)
{
vis[re] = true;
num++;
int len = vec[re].size();
for(int i = 0; i < len; i++)
{
int e = vec[re][i];
if(vis[e]) continue;
dfs(e, num);
}
}
int main()
{
scanf("%lld%lld", &n, &k);
for(int i = 1; i < n; i++)
{
ll x, y, z;
scanf("%lld%lld%lld", &x, &y, &z);
if(z) continue;
vec[x].push_back(y);
vec[y].push_back(x);
}
ans = pow_fast(n, k);
for(int i = 1; i <= n; i++)
{
if(!vis[i])
{
ll num = 0;
dfs(i, num);
ans = (ans - pow_fast(num, k) + mod) % mod;
}
}
printf("%lld\n", ans);
return 0;
}