HDU 1936 Emoticons :-) (贪心)
题目
http://acm.hdu.edu.cn/showproblem.php?pid=1936
题意
给n个表情,m个字符串(带空格),求最少需要破坏多少个字符(替换成空格),使得字符串中不存在表情
解法
对于每个字符串,搜索出每个表情出现的位置,记录成一个个区间,于是就转换成,区间选点问题,选择最少的点覆盖全部区间。
对所有区间先按右端点从小到大排序,右端点相同时按左端点从大到小排序,第一次选择第一个区间的右端点,对于后面的区间,若\(p[i].x > temp\), 则\(ans+1,temp = p[i].y\)
代码
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
const int N = 110;
struct Node {
int x, y;
} p[N];
int cmp(Node a, Node b) {
if(a.y == b.y)
return a.x > b.x;
return a.y < b.y;
}
int main() {
string E[N], t;
int n, m;
while(cin >> n >> m && n) {
for(int i = 0; i < n; i++)
cin >> E[i];
getchar();
int ans = 0;
while(m--) {
getline(cin, t);
int lent = t.size();
int cnt = 0;
for(int i = 0; i < n; i++) {
int lene = E[i].size();
int pos = 0;
while(pos < lent && t.find(E[i], pos) != t.npos) {
p[cnt].x = t.find(E[i], pos);
p[cnt].y = p[cnt].x + lene - 1;
pos = p[cnt].x + 1;
cnt ++;
}
}
if(cnt == 0)
continue;
sort(p, p + cnt, cmp);
ans ++;
int temp = p[0].y;
for(int i = 0; i < cnt; i++) {
if(p[i].x > temp) {
ans ++;
temp = p[i].y;
}
}
}
cout << ans << endl;
}
return 0;
}