Master-Mind Hints UVA - 340
题目传送门:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=276
题目大意:寻找字符串位置是否正确,首先给出一个正确的序列,然后给出数个猜想序列,若是猜想序列位置i上的数字与正确序列位置j上的数字相同,若i = j则称之为强匹配,否则若i != j,则称之为弱匹配;
要求输出一个强弱匹配数的序偶;
注意:强匹配上的数字不能作为判断弱匹配的选项;
一定要注意输出格式;
Sample Input
4
1 3 5 5
1 1 2 3
4 3 3 5
6 5 5 1
6 1 3 5
1 3 5 5
0 0 0 0
10
1 2 2 2 4 5 6 6 6 9
1 2 3 4 5 6 7 8 9 1
1 1 2 2 3 3 4 4 5 5
1 2 1 3 1 5 1 6 1 9
1 2 2 5 5 5 6 6 6 7
0 0 0 0 0 0 0 0 0 0
0
Sample Output
Game 1:
(1,1)
(2,0)
(1,2)
(1,2)
(4,0)
Game 2:
(2,4)
(3,2)
(5,0)
(7,0)
一开始写的比较复杂的代码
效率不高,切代码冗长,不过也可以无伤通过
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
vector<int>v,s,v1;
int cnt = 0;
int n;
int key;
int strongnum;
int weaknum;
int strong()
{
int sum = 0;
int k = n;
for(int i = 0; i < k; i++)
{
if(s[i] == v1[i])
{
v1.erase(v1.begin()+i);
s.erase(s.begin()+i);
sum++;
i--;
k--;
}
}
return sum;
}
int weak()
{
int sum = 0;
int k = n;
for(int i = 0; i < k - strongnum; i++)
{
for(int j = 0; j < k-strongnum; j++)
{
if(s[i] == v1[j])
{
sum++;
s.erase(s.begin()+i);
v1.erase(v1.begin()+j);
i--;
j--;
k--;
}
}
}
return sum;
}
int main()
{
while(cin>>n)
{
cnt++;
if(n == 0)
break;
for(int i = 0; i < n; i++)
{
cin>>key;
v.push_back(key);
}
int flag = 1;
cout<<"Game "<<cnt<<":"<<endl;
while(flag)
{
s.clear();
v1.clear();
v1.assign(v.begin(),v.end());
for(int j = 0; j < n; j++)
{
cin>>key;
s.push_back(key);
if(key == 0)
flag = 0;
}
if(!flag)
break;
strongnum = strong();
weaknum = weak();
cout<<" ("<<strongnum<<","<<weaknum<<")"<<endl;
}
v.clear();
}
return 0;
}
后来参考了刘汝佳的《算法竞赛入门经典》写的效率较高的代码
#include <iostream>
#include <bits/stdc++.h>
#define maxn 1005
using namespace std;
int main()
{
int n,i,d,x,y,num1,num2,times=0;
int a[maxn],b[maxn];
while(scanf("%d",&n)==1 && n)
{
printf("Game %d:\n",++times); //数据组数编号
for(i = 0; i < n; i++)
scanf("%d",&a[i]);
for(;;)
{
x = 0;
y = 0;
for(i = 0; i < n; i++)
{
scanf("%d",&b[i]);
if(a[i] == b[i]) x++; //统计有多少数字位置正确
}
if(b[0] == 0) break;
for(d = 1; d < 10; d++)//因为限制了只有1-9的范围所以很大程度上节省了时间,提高效率
{
num1=0;
num2=0;
for(i = 0; i<n; i++)
{
if(d == a[i]) num1++;
if(d == b[i]) num2++;
}
if(num1 < num2) y += num1;
else y += num2;
}
printf(" (%d,%d)\n",x,y-x);//注意输出格式
}
}
return 0;
}