牛客练习赛51 A B C

文章目录

  • A
  • B
  • C

A

前后缀维护字符串中b左边a的个数和b的个数,对于每个b,它能构成的的abc的个数即为它前面a的个数乘以它后面c的个数

#include
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
typedef pair<int,int> pii;
string s;
const int maxn = 1e5+10;
ll a[maxn],c[maxn];
int main()
{
    ios::sync_with_stdio(false);
    cin>>s;
    int len = s.size();
    for (int i = 0;i < len;i ++)
    {
    	a[i+1] = a[i];
    	if (s[i] == 'a') ++a[i+1] ;
    }
    for (int i = len - 1;i >= 0;-- i)
    {
    	c[i] = c[i+1];
    	if (s[i] == 'c') ++ c[i]; 
    }
    ll ans = 0;
    for (int i = 1;i < len - 1;++ i)
    	if (s[i] == 'b') ans += a[i] * c[i+1];
    cout<<ans<<'\n';
    return 0;
}

B

用一个数组pos[i][j]记录 i 之后最近的字母 j 的位置

#include
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
typedef pair<int,int> pii;
string s1,s2;
int n,q;
const int maxn = 1e5 + 10;
int pos[maxn][30];
int solve()
{
	int len = s2.size();
	int i = 0,j = -1;
	while (i < len)
	{
		j = pos[j+1][s2[i++]-'a'];
		if (j == -2) return 0;
	}
	return 1;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>q;
    cin>>s1;
    for (int i = 0;i < 28;i ++) pos[n][i] = -2;
    for (int i = n - 1;i >= 0;-- i)
    {
    	for (int j = 0;j < 26;++ j) pos[i][j] = pos[i+1][j];
    	pos[i][s1[i]-'a'] = i;
    }
    while (q --)
    {
    	cin>>s2;
    	if (solve()) cout<<"YES"<<'\n';
    	else cout<<"NO"<<'\n';
    }
    return 0;
}

C

勾股数

#include
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
typedef pair<int,int> pii;
 
int main()
{
    ios::sync_with_stdio(false);
    ll n;
    cin>>n;
    if (n & 1)
    {
        if (n == 1) cout<<-1<<'\n';
        else
        {
            n /= 2;
            ll x = 2*n*n+2*n;
            cout<<x<<' '<<x+1<<'\n';
        }
    }
    else
    {
        if (n < 4) cout<<-1<<'\n';
        else if (n == 4) cout<<3<<' '<<5<<'\n';
        else
        {
            n >>= 1;
            ll x = n*n-1;
            cout<<x<<' '<<x + 2<<'\n';
        }
    }
    return 0;
}

你可能感兴趣的:(牛客网)