L1-095 分寢室 分數 20

Frodnx發表於2024-08-24

想得太複雜,這道題不會卡你人數為0時候的情況,不要忘記題目的條件:不允許單人住一間寢室

// 32'41"
#include <bits/stdc++.h>
using namespace std;
map<int,bool> div(int x)
{
    map<int,bool> hash;
    if(x == 0) hash[0] = true;
    for(int i = 1; i <= x; ++ i)
        if(x % i == 0) hash[i] = true;
    return hash;
}
int main()
{
    int m, w, s;
    cin >> m >> w >> s;
    if(m == 0 && w == 0 && s == 0)
    {
    	cout << "0 0";
    	return 0;
	}
	if(s == 0)
	{
		cout << "No Solution";
		return 0;
	}
    auto hm = div(m);
    auto hw = div(w);
    int res1 = -1, res2 = -1;
    for(auto hi : hm)
    {
    	int manroom = hi.first;
        int womanroom = s - hi.first;
        if(manroom == m || womanroom == w) continue;
        //cout << "hi: " << hi.first << " " << tmp << endl;
        if(hw[womanroom] == true)
        {
        	//cout << res1 << " " << res2 << endl;
        	if(manroom == 0)
        	{
        		res1 = 0, res2 = s;
        		break;
			}
			if(womanroom == 0)
			{
				res1 = s, res2 = 0;
        		break;
			}
            int nres1 = m / manroom;
            int nres2 = w / womanroom;
            if(abs(nres1 - nres2) < abs(res1 - res2) || res1 == -1 || res2 == -1)
                res1 = nres1, res2 = nres2;
        }
    }
    if(res1 == -1 && res2 == -1) cout << "No Solution";
    else if(res1 != 0 && res2 != 0) cout << m / res1 << " " << w / res2;
    else cout << res1 << " " << res2;
    return 0;
}

相關文章