P4875 [USACO14OPEN]Fair Photography G 题解
模拟赛考到这题了,跟风 yspm 写篇题解
翻译
code
省略的头文件
const int N = 1e5+5;
int n,m;
PII a[N];
int ans=-1,lst[10],sum[N][10]; // lst记录每个品种上次出现的位置
PII tmp[10];
unordered_map<ULL,int> mp; // hash表
ULL hsh(int s,int i) { // hash函数
int fi = 7; For(j,0,7) if( s & (1<<j) ) { fi = j; break; }
ULL res = 0;
For(j,fi+1,7) if( s & (1<<j) ) res = res * 997 + sum[i][j]-sum[i][fi];
return res;
}
signed main() {
read(n,m); --m;
For(i,1,n) read(a[i].fi,a[i].se), --a[i].se; sort(a+1,a+n+1);
For(i,1,n) {
mp[0] = a[i].fi;
For(j,0,7) sum[i][j] = sum[i-1][j]; ++sum[i][a[i].se];
For(j,lst[a[i].se]+1,i) { // 暴力修改
int s = 0; For(k,0,7) if( sum[i-1][k]-sum[j-1][k] ) s |= 1<<k;
mp.erase(hsh(s,j-1)); // 删去原来状态
s |= 1<<a[i].se; ULL h = hsh(s,j-1);
if( !mp.count(h) ) mp[h] = a[j].fi; // 更新当前状态
}
lst[a[i].se] = i;
// s为当前集合,tmp按每个品种最后一次出现的位置排序加入s
For(j,0,7) tmp[j] = MP(lst[j],j); sort(tmp,tmp+8,greater<PII>());
int s = 0; For(j,0,m-1) s |= 1 << tmp[j].se;
for(int j = m; j < 8 && tmp[j].fi; ++j) {
s |= 1 << tmp[j].se;
ULL h = hsh(s,i);
if( mp.count(h) ) ckmax(ans,a[i].fi-mp[h]);
}
}
write(ans);
return iocl();
}