UVa 10125 Sumsets

解題策略

這題的解法很直接,要找d=a+b+c
用四層迴圈下去跑a,b,c,d就好了 XDDDD

我犯了幾個錯誤
  1. 要找最大符合d (意思是數列中可能出現好幾個符合要求的解),所以迴圈應該由最大元素往下找,第一個找到的解就是答案,我一開始由最小元素往上遞增尋找,拿了WA。
  2. 沒找到解就回傳0,殊不知0也有可能是解: 0 = -5 + 3 + 2,這裡也吃了一個WA,所以我後來改回傳 INT_MAX 作為無解。
這題有負值,所以 -5 = -10 + -2 + 7 ,這樣算一組合法的解。
是比較需要小心的地方。

官網論壇上的(a+b)=(d-c)法,方法複雜很多,卻沒有比較快。

/**
* UVa 10125 Sumsets (AC)
* Author: chchwy
* Last Modified: 2010.03.18
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int find(vector<int>& set)
{
for (int d = set.size() - 1; d >= 0; --d) // find the largest d
for (int a = 0; a < set.size(); ++a)
for (int b = a + 1; b < set.size(); ++b)
for (int c = b + 1; c < set.size(); ++c)
if ( (set[d] == set[a] + set[b] + set[c]) &&
a != d && b != d && c != d )
return set[d];
return INT_MAX;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("10125.in", "r", stdin);
#endif
int numElement;
while (cin >> numElement)
{
if (numElement == 0)
break;
/* input */
vector<int> set(numElement);
for (int i = 0; i < numElement; ++i)
cin >> set[i];
sort(set.begin(), set.end());
/* find d = a + b + c */
int d = find(set);
if ( d == INT_MAX )
cout << "no solution\n";
else
cout << d << "\n";
}
return 0;
}
view raw 10125.cpp hosted with ❤ by GitHub

留言

這個網誌中的熱門文章

讀書心得: 撒哈拉的故事

讀書心得: 你以為你以為的就是你以為的嗎?