Problem Statement
從一串數中取數,取走其中一個數的時候,要連帶取走與其相鄰的數字(例如:取走10,若數串中有9和11,就也都取走)。
要求:給一串數,設計算法,使得取數的次數最多。
Definition
Class: | SRMCards |
Method: | maxTurns |
Parameters: | vector <int> |
Returns: | int |
Method signature: | int maxTurns(vector <int> cards) |
(be sure your method is public) |
Constraints
- |
cards will contain between 1 and 50 elements, inclusive. |
- |
Each element of cards will be between 1 and 499, inclusive. |
- |
All elements of cards will be distinct. |
Basic Thoughts
爲了能讓取數的次數最多,需要如下做:
1. 挑出沒有相鄰項的數字,取出它;
2. 挑出有一個相鄰項的數字,取出它以及它的相鄰項;
3. 絕不允許出現取出有兩個相鄰項的數字。
所以,算法判斷時只有上述1,2兩種可能的情況。按上述兩種情況取數,直到所有數字被取完爲止。
class SRMCards
{
// basic strategy
// 1. pick up the number which has no neighbor and remove it
// 2. pick up the number which has one neighbor and remove them two and go back to 1
public:
int maxTurns(vector <int> cards)
{
int res = 0;
int count = cards.size();
int len = cards.size();
int j;
for(j=0;j<2;j=(++j)%2)
{
for(int i=0;i<len;i++)
{
if(cards[i] != -1)
{
vector<int>::iterator card1 = find(cards.begin(),cards.end(),cards[i]-1);
vector<int>::iterator card2 = find(cards.begin(),cards.end(),cards[i]+1);
if (j == 0 && card1 == cards.end() && card2 == cards.end())
{
res++;
cards[i] = -1;
count--;
}
else if (j == 1 && card1 == cards.end() && card2 != cards.end())
{
res++;
cards[i] = -1;
*card2 = -1;
count-=2;
}
else if (j == 1 && card2 == cards.end() && card1 != cards.end())
{
res++;
cards[i] = -1;
*card1 = -1;
count-=2;
}
else continue;
}
}
if (count == 0)
{
break;
}
}
return res;
}
};