一.四色花环
以下代码的三个问题:(1)像333444451这种数字串无法得到最长的相同数字组成的子序列;(2)cnt无法准确计数出重复子序列中相同数的个数,例如4444,cnt会计数出6;(3)最后计算需要的总操作次数公式错误。
#include<iostream>
using namespace std;
int root[5];
int main()
{
int t;
cin >> t;
while (t--)
{
for (int i = 0; i < 4; i++) cin >> root[i];
int tag = 0;
int cnt = 0;
for (int i = 0; i < 4; i++)
{
for (int j = i + 1; j < 4; j++)
{
if (root[i] == root[j])
{
tag = root[i];
if (root[i] == tag) cnt++;
}
}
}
int remained = 4 - cnt;
if (remained >= cnt - 1) cout << "4" << endl;
else if (remained % 2 == 0) cout << 2 * cnt - 1 << endl;
else cout<<2* cnt << endl;
}
}
 以下代码是正确的——
#include<iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
//不能用整数数组读入,因为输入数据并不会换行!
char s[5];
cin >> s;
int mx = 0;
for (int i = 0; i < 4; i++)
{
int cnt = 1;
for (int j = i + 1; j < 4; j++)
{
if (s[i] == s[j])
{
cnt++;
//mx有两个作用,一是防止组合数对计数的影响,二是计算出最长的重复子序列
mx = cnt > mx ? cnt : mx;
}
}
}
int remained = 4 - mx;
if (mx == 4) cout << " -1 " << endl