列表

详情


NC237451. Subsegments

描述

You are given an array of integers and an integer x.

Output the number of subsegments where such that .

输入描述

The first line contains two integers n and x (, ).

The second line contains n numbers .

输出描述

Output one integer, the answer.

示例1

输入:

10 6
2 3 2 1 6 2 3 2 1 7

输出:

8

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(g++ 7.5.0) 解法, 执行用时: 751ms, 内存消耗: 63032K, 提交时间: 2022-09-24 10:03:48

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mod=998244353;
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	ll n,x;
	cin>>n>>x;
	map<ll,ll> mp;
	ll ans=0;
	if(x){
	ll res=1;
	mp[x]=1;
	for(int i=1;i<=n;i++){
		ll y;
		cin>>y;
		res=(res*y)%mod;
		if(res==0){
			res=1;
			mp.clear();
			mp[x]++;
            continue;
		}
		ans=ans+mp[res];
		ll k=(res*x)%mod;
		mp[k]++;
	}
	}
	else{
		if(x==0){
		ll tag=0;
		for(int i=1;i<=n;i++){
			ll y;
			cin>>y;
			if(y==0){
				ans=ans+(i-tag)*(n-i+1);
				tag=i;
			}
		}
	}
	}
	cout<<ans<<"\n";
	return 0;
}

C++ 解法, 执行用时: 749ms, 内存消耗: 58228K, 提交时间: 2022-05-26 00:17:29

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=5e5+7,mod=998244353;
unordered_map<ll,ll>mp;
ll s[N];
int main()
{
	ll n,x,t,ans=0,l=0;
	cin>>n>>x;
	if(x==0){
		for(ll i=1;i<=n;i++){
			cin>>t;
			if(t==0){
				ans+=(i-l)*(n-i+1);
				l=i;
			}
		}
	}
	else{
		s[0]=1;
		for(ll i=1;i<=n;i++){
			cin>>t;
			if(t!=0){
				s[i]=s[i-1]*t;
				s[i]%=mod; 
				if(s[i]==x) ans++;
				ans+=mp[s[i]];
				mp[(s[i]*x)%mod]++;
			}
			else{
				mp.clear();
				s[i]=1;
			}
		}
	}
	cout<<ans;
	return 0;
 } 

上一题