TCO14 2B L3: AlwaysDefined,math,从余数入手

解析复杂数分类算法及其实现细节
本文深入探讨了一种用于将数按对W的余数进行分类的算法实现,详细阐述了其核心思想、代码逻辑以及解决复杂问题的策略。通过实例分析,展示了如何在编程中清晰地组织思维,有效解决实际问题。

题目:http://community.topcoder.com/stat?c=problem_statement&pm=13060&rd=15996

参考:http://apps.topcoder.com/wiki/display/tc/TCO+2014+Round+2B

将数按对W的余数进行分类。做题思维要非常清晰,难度不小,看题解看了半天才看懂。

代码:

#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <sstream>
#include <iomanip>

#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;

#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)
typedef pair<int, int> pii;
typedef long long llong;
typedef pair<llong, llong> pll;
#define mkp make_pair

/*************** Program Begin **********************/
vector<vector<int>> g;

class AlwaysDefined {
public:
	inline long long items(long long rem, long long upper, int W)
	{
		// rem + (cnt - 1) * W < upper
		long long numbers = upper - rem;
		return (numbers + W - 1) / W;
	}
	long long solve(int W, int rem, long long cnt)
	{
		if (cnt <= 0) {
			return 0;
		}
		if (1 == rem) {
			return cnt;
		}
		long long ans = 0;
		for (int i = 0; i < g[rem].size(); i++) {
			int x = g[rem][i];
			long long smallest = rem + x * W;
			long long newrem = smallest / rem;
			ans += solve(W, newrem, items(x, cnt, rem));	// rem 为一个周期
		}
		return ans;
	}

	long long countIntegers(long long L, long long R, int W) {
		long long res = 0;
		g.resize(W);
		for (int i = 0; i < g.size(); i++) {
			g[i].clear();
		}
		for (int rem = 1; rem < W; rem++) {
			for (int x = 0; x < rem; x++) {
				if ( (x * W) % rem == 0 ) {
					g[rem].push_back(x);
				}
			}
		}
		for (int rem = 1; rem < W; rem++) {
			res += solve(W, rem, items(rem, R + 1, W));
			res -= solve(W, rem, items(rem, L, W));
		}

		return res;
	}

};

/************** Program End ************************/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值