D. Polycarp and Div 3 Codeforces Round #496 (Div. 3) 利用简单的贪心破解数论问题

友情链接:http://acm.hdu.edu.cn/showproblem.php?pid=2037

在HDU2037的问题中给出了我们对不同【s,t】区间找最多不重复段数的方法

我们可以通过扫描从每个位置开始,最短的三的倍数,获得一系列三的倍数的区间,再排序一下就解决了这个问题。

#include<cstdio>
#include<vector>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
struct Line{
	int s, t;
	bool operator < (const Line& x)const {
		return t < x.t;
	}
};
Line l[200005];
char s[200005];
int main(){
	scanf("%s", s);
	int sum;
	int len = strlen(s);
	int cnt = 0;
	for (int i = 0; s[i]; i++) {
		sum = 0;
		for (int j = i; s[j]; j++) {
			sum = sum + (s[j] - '0');
			if ((sum) % 3 == 0) {
				l[cnt].s = i;
				l[cnt++].t = j;
				break;
			}
		}
	}
	int t = 0;
	if (cnt > 0) {
		sort(l, l + cnt);
		t = 1;
		int e1 = l[0].t;
		for (int i = 1; i < cnt; i++) {
			if (e1 < l[i].s) {
				++t;
				e1 = l[i].t;
			}
		}
	}
	printf("%d", t);
#ifdef SunWei
	system("pause");
#endif
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41104612/article/details/81162382