1. 程式人生 > 其它 >CodeForces - 364A Matrix(思維+數學)

CodeForces - 364A Matrix(思維+數學)

技術標籤:思維數學

題目連結:點選檢視

題目大意:給出一個長度為 n 的,只由十進位制數字組成的字串 s,可以構造出一個大小為 n * n 的矩陣,構造方法如下:b[ i ][ j ] = s[ i ] * s[ j ],現在問有多少個子矩陣的權值和等於 sum

題目分析:雖然 n 比較小,但如果模擬出陣列 b 然後再求二維字首和的話就有點麻煩了,這個題的模型和昨天做的那個題差不多:CodeForces - 1425D

上面的那個題是需要將完全平方和拆開,而這個題恰恰相反,是需要將完全平方和合起來,考慮一個區間內的權值和:\sum_{i=x1}^{x2}\sum_{j=y1}^{y2}b[i][j],這個是兩層for迴圈遍歷所有的元素然後加和,模仿完全平方公式,我們不難推出更簡單的公式:(sum[x2]-sum[x1-1])*(sum[y2]-sum[y1-1])

因為一個矩形可以視為兩個線段,一個是 x 方向的,一個是 y 方向的,上面的公式的兩個乘數分別與其對應

這樣一來我們就可以預處理出 y 方向上的所有 “線段”,再列舉 x 方向的每個 “線段” ,然後去 y 方向上去找到對應的與其匹配即可

不過需要特判一下 sum = 0 的情況,下面考慮一下 0 的貢獻,假設 s[ i ] == 0,那麼會使得 b 陣列的第 i 行和第 i 列的取值都是 0,一行會產生 n * ( n + 1 ) / 2 個滿足條件的子矩陣,而第 i 行和第 i 列同時為 0 的話,就會產生 n * ( n + 1 ) / 2 * 2 = n * ( n + 1 ) 個子矩陣,不過需要注意一下,b[ i ][ i ] 這個格子被計算了兩次,所以需要減去

那麼假設字串 s 中共有 cnt[ 0 ] 個 “線段” 的取值為 0,那麼這些 “線段” 既有 x 方向上的,又有 y 方向上的,根據上面容斥的擴充套件,總共是有 cnt[ 0 ] * n * ( n + 1 ) - cnt[ 0 ] * cnt[ 0 ] 個滿足條件的子矩陣

程式碼:

//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
using namespace std;
 
typedef long long LL;
 
typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=1e6+100;

char s[N];

LL cnt[N];

int sum[N];

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.ans.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	int a;
	scanf("%d",&a);
	scanf("%s",s+1);
	int n=strlen(s+1);
	for(int i=1;i<=n;i++)
		sum[i]=sum[i-1]+s[i]-'0';
	for(int i=1;i<=n;i++)
		for(int j=1;j<=i;j++)
			cnt[sum[i]-sum[j-1]]++;
	if(a==0)
	{
		printf("%lld\n",cnt[0]*n*(n+1)-cnt[0]*cnt[0]);
		return 0;
	}
	LL ans=0;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=i;j++)
		{
			int num=sum[i]-sum[j-1];
			if(num!=0&&a%num==0&&a/num<N)
				ans+=cnt[a/num];
		}
	printf("%lld\n",ans);












    return 0;
}