2 条题解

  • 0
    @ 2024-9-22 20:44:48

    题解:

    #include <bits/stdc++.h>
    using namespace std;
    
    int a[11];
    bool vis[11][2];
    long long f[11][2], cnt[11][2];
    
    long long dfs(int p, bool limit) {
    	if (vis[p][limit])
    		return f[p][limit];
    	if (p == 0) {
    		vis[p][limit] = true;
    		int up = limit ? a[p] : 9;
    		f[p][limit] = (1 + up) * up / 2;
    		cnt[p][limit] = up + 1;
    		return f[p][limit];
    	}
    	vis[p][limit] = true;
    	int up = limit ? a[p] : 9;
    	for (int i = 0; i <= up; i++) {
    		// 第 p 位选为了 i
    		int li = limit && i == up;
    		dfs(p-1, li);
    		f[p][limit] += f[p-1][li] + cnt[p-1][li] * i;
    		cnt[p][limit] += cnt[p-1][li];
    	}
    	return f[p][limit];
    }
    
    long cal(int num) {
    	memset(vis, 0, sizeof vis);
    	memset(f, 0, sizeof f);
    	memset(cnt, 0, sizeof cnt);
    	int p = 0;
    	for (; num; a[p++] = num % 10, num /= 10);
    	return dfs(p-1, true);
    }
    
    int main() {
    	int l, r;
    	cin >> l >> r;
    	cout << cal(r) - cal(l-1) << endl;
    	return 0;
    }
    
    • 0
      @ 2024-9-22 20:17:28

      数位搜索(演示通过 dfs 的形式输出 0 ~ a):

      #include <bits/stdc++.h>
      using namespace std;
      
      int a[11], b[11];
      void dfs(int p, bool limit) {
      	if (p < 0) {
      		cout << "number: ";
      		for (int i = 10, f = 0; i >= 0; i--) {
      			if (b[i] || i == 0) f = 1;
      			if (f) cout << b[i];
      		}
      		cout << endl;
      		return;
      	}
      	int up = limit ? a[p] : 9;
      	for (int i = 0; i <= up; i++) {
      		b[p] = i;
      		dfs(p-1, limit && i == up);
      	}
      }
      
      void cal(int num) {
      	int p = 0;
      	for (; num; a[p++] = num % 10, num /= 10);
      	// a[p-1..0]
      	dfs(p-1, true);
      }
      
      int main() {
      	int a;
      	cin >> a;
      	cal(a);
      	return 0;
      }
      
      • 1

      信息

      ID
      39
      时间
      1000ms
      内存
      256MiB
      难度
      10
      标签
      (无)
      递交数
      4
      已通过
      3
      上传者