题解:UVA12527 Different Digits

· · 题解

翻译

某某地区的居民非常迷信,有重复数字的门牌号会给他们带来厄运,他们不会住在有重复数字的门牌号的房间里。

分析

题意就是让你在一个区间里面找所有数位上的数都不一样的数。

大概思路就是循环枚举这个区间的每个数,用函数判断下,满足要求则计数器加一。

函数作用就是枚举数位和检查,a 数组用来累计数位上数出现的次数,每次要清空。如果这个数已经出现过一定不符合要求,否则就把这个数标记。

#include<bits/stdc++.h>
using namespace std;
int l,r;
bool check(int x){//判断函数
    bool a[10];
    memset(a,0,sizeof(a));//清空操作
    while(x!=0){//枚举数位
        if(a[x%10]) return 0;//如果这个数已经出现过一定不符合要求
        a[x%10]=1;//否则标记
        x/=10;//继续循环
    }
    return 1;//如果执行到这里一定是符合要求的
}
signed main(){
    //freopen("a.in","r",stdin);
    //freopen("a.out","w",stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    while(cin>>l>>r){//while循环输入
        int ans=0;//多测清空
        for(int i=l;i<=r;i++){
            if(check(i)){
                ans++;//计数器加加
            }
        }
        cout<<ans<<endl;//要换行!!!
    }
    return 0;
}

当然,这个代码是可以优化滴。

数据范围只有五千多。我们可以用一个小记忆化,预处理出所有的结果,这样,仅需运算一遍就可以解决所有的访问,即取即用,非常方便,而且时间更优。

优化后代码:

#include<bits/stdc++.h>
using namespace std;
int l,r;
int b[5005];
bool check(int x){//判断函数
    bool a[10];
    memset(a,0,sizeof(a));//清空操作
    while(x!=0){//枚举数位
        if(a[x%10]) return 0;//如果这个数已经出现过一定不符合要求
        a[x%10]=1;//否则标记
        x/=10;//继续循环
    }
    return 1;
}
signed main(){
    //freopen("a.in","r",stdin);
    //freopen("a.out","w",stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    for(int i=1;i<=5005;i++){
        b[i]=check(i);//预处理 
    } 
    while(cin>>l>>r){//while循环输入
        int ans=0;
        for(int i=l;i<=r;i++){
            ans+=b[i];//比if更方便 
        }
        cout<<ans<<endl;//要换行
    }
    return 0;
}