题解:P17200 DKM OI Round 1 - 彩带拼接
moumouxiugou · · 题解
彩带拼接 题解
这是本蒟蒻第一篇题解,用了AI进行了稍微修改,不过能够保证我写的原文是大于AI修改的,如有错误请大佬指正
Ciallo~(∠・ω< )⌒☆
题目大意
有
解题思路
本题是带颜色限制的 0/1 背包。每个彩带只能选一次,且相邻颜色不能相同,相当于我们在拼接时不仅要记录当前总长度,还要记录最后一条彩带的颜色,以避免重复。
直接开二维
这样,当我们在状态
- 若
c \ne col[j] ,则可以从\(f[j]\) 转移; - 若
c = col[j] ,则不能从\(f[j]\) 转移(会颜色相同),只能从\(g[j]\) 转移。
转移后需要更新
状态转移
设当前彩带长度为
枚举长度
if (\(f[j]\) == NEG) continue;
long long base = (col[j] == c ? \(g[j]\) : \(f[j]\));
if (base == NEG) continue;
long long nv = base + v;
int nj = j + l;
更新
- 若
nv > \(f[nj]\) :- 原来的
\(f[nj]\) 变成次优,但仅当原来的颜色不等于c 时才能放入\(g[nj]\) (否则g 不能与f 颜色相同)。 - 更新
\(f[nj]\) = nv ,\(col[nj]\) = c 。
- 原来的
- 否则,若
nv > \(g[nj]\) 且\(col[nj]\) \ne c ,则更新\(g[nj]\) = nv 。
初始化
-
- 所有其他状态设为
-\infty 。
答案
最终若
复杂度
- 时间复杂度:
O(n \cdot L) ,其中n \le 10^3 ,L \le 10^5 ,可接受。 - 空间复杂度:
\(O(L)\) 。
参考代码
#include<bits/stdc++.h>
using namespace std;
const int MAXL=100005;
const long long NEG=-4e18;
long long f[MAXL], g[MAXL];
int col[MAXL];
int main(){
ios::sync_with_stdio(0);cin.tie(0);
int n, L;
cin>>n>>L;
for(int i=0;i<=L;i++) \(f[i]\)=\(g[i]\)=NEG;
\(f[0] = 0\); \(col[0] = 0\);
for(int i=1;i<=n;i++){
long long l, v, c;
cin>>l>>v>>c;
for(int j=L-l;j>=0;j--){
if(\(f[j]\)==NEG) continue;
long long base = (col[j]==c ? \(g[j]\) : \(f[j]\));
if(base==NEG) continue;
long long nv = base+v;
int nj = j+l;
if(nv>\(f[nj]\)){
if(\(col[nj]\)!=c) \(g[nj]\)=\(f[nj]\);
\(f[nj]\)=nv;
\(col[nj]\)=c;
} else if(nv>\(g[nj]\) && \(col[nj]\)!=c){
\(g[nj]\)=nv;
}
}
}
if(\(f[L]\)==NEG) cout<<-1<<"\n";
else cout<<\(f[L]\)<<"\n";
return 0;
}
OWO
其实变量没必要写的详细,早就知道用a,b,c了
注意事项
- 使用
long long存储美观度,因为n \times v_i 最大可达10^3 \times 10^3 = 10^6 ,但保险起见用long long。 - 逆序枚举长度保证每个彩带只使用一次。
- 更新g时需判断 (col[nj])!=c,确保次优颜色与最优不同,保持语义正确。
本题解就讲到这里,感谢各位神犇的观看(•̀ω•́)✧我们下一篇文章见
半角空格还是太恶心了