题解:UVA12765 Factorial Products

· · 题解

题意

给你 n + m 个数,判断前 n 个数的阶乘乘积是否等于后 m 个数的阶乘乘积。

思路

运用分数的性质。我们这里称呼前 n 个数的阶乘乘积为 x,后 m 个数的阶乘乘积为 y。我们根据题意,这里假设乘积相同,列出 \frac{x}{y} = 1,由此得到 \frac{x \div z}{y \div z} = 1 \left ( z \ge 1 \right ) 。所以,分子和分母同时除以不为 0 的数,分数值不变。
这里可以用桶,为什么呢?因为我们可以在前 n 个数加加,后 m 个数减减,就可以做到抵消的作用,同时最后统计的时候记得用绝对值,因为有可能会变成负数。

代码

#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
const int N=10005;
int t[N];
int x,n,m,maxn,y;
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    while(cin>>n>>m&&n!=0&&m!=0){
        maxn=0;
        for(int i=1;i<=n;i++){
            cin>>x;
            maxn=max(maxn,x);
            for(int j=1;j<=x;j++) t[j]++;
        }
        for(int i=1;i<=n;i++){
            cin>>x;
            maxn=max(maxn,x);
            for(int j=1;j<=x;j++) t[j]--;
        }
        //如果有相同的t一加一减会抵消
        x=y=1;
        for(int i=1;i<=maxn;i++){
            if(t[i]<0){
                for(int j=1;j<=abs(t[i]);j++) x*=i;
            }
            else{
                for(int j=1;j<=abs(t[i]);j++) y*=i;
            }
            //必须是abs(t[i])因为t[i]可能为负 
        }
        cout<<(x==y?"Yes\n":"No\n");
    }
    return 0;
}