其他分享
首页 > 其他分享> > Mysterious Crime CodeForces - 1043D (哈希)

Mysterious Crime CodeForces - 1043D (哈希)

作者:互联网

大意: 给定m个n排列, 求有多少个公共子串.

 

枚举每个位置, hash求出最大匹配长度. 

#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
#define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;})
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;}
//head



const int N = 1e5+10;
int n, m, s[12][N];
int pos[12][N];
int bas[N], has[12][N];
int Hash(int id, int l, int r) {
	int ret = (has[id][r]-(ll)has[id][l-1]*bas[r-l+1])%P;
	if (ret<0) ret += P;
	return ret;
}
int calc(int x, int p1, int y, int p2) {
	int l=1,r=min(p1,p2),ans=-1;
	while (l<=r) {
		if (Hash(x,p1-mid+1,p1)==Hash(y,p2-mid+1,p2)) ans=mid,l=mid+1;
		else r=mid-1;
	}
	return ans;
}
int main() {
	scanf("%d%d", &n, &m);
	bas[0] = 1, bas[1] = n*20+1;
	REP(i,2,n) bas[i]=(ll)bas[i-1]*bas[1]%P;
	REP(i,1,m) REP(j,1,n) { 
		scanf("%d", s[i]+j);
		has[i][j] = ((ll)has[i][j-1]*bas[1]+s[i][j])%P;
		pos[i][s[i][j]] = j;
	}
	if (m==1) return printf("%lld\n",(ll)n*(n+1)/2),0;
	ll ans = 0;
	REP(i,1,n) {
		int d = 1e9;
		REP(j,2,m) d = min(d, calc(1,i,j,pos[j][s[1][i]]));
		ans += d;
	}
	printf("%lld\n", ans);
}

 

标签:a%,int,ll,1043D,CodeForces,Mysterious,return,include,define
来源: https://www.cnblogs.com/uid001/p/10914033.html