題目在此 http://zerojudge.tw/ShowProblem?problemid=a291
首先需要了解此題的規則,例如測試資料為
8 4 7 5
4
1 2 3 4
8 1 2 4
4 7 5 8
8 4 7 5
輸出結果會是
1234 ==> 0A1B
8124 ==> 1A1B
4758 ==> 0A4B
8475 ==> 4A0B
了解以上的規則後,就可以用比對的方式計算出有多少個 A與多少個 B了。
可用一層迴圈算出幾個 A。
可用兩層迴圈算出幾個 B。
程式碼:
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int CNT = 4;
int answer[CNT];
int guess[CNT];
int idx = 0;
int round = 0;
while( scanf("%d %d %d %d", &answer[0], &answer[1], &answer[2], &answer[3])!=EOF ) {
scanf("%d", &round);
int a[round] = { 0 };
int b[round] = { 0 };
idx = 0;
while( idx < round ) {
int guessIdx = 0;
int found[CNT] = { 0 };
while( guessIdx < CNT ) {
scanf("%d", &guess[guessIdx]);
// How many A.
if(guess[guessIdx] == answer[guessIdx]) {
a[idx]++;
found[guessIdx] = 1;
} else {
found[guessIdx] = 0;
}
guessIdx++;
}
// How Many B.
for( guessIdx = 0; guessIdx < CNT; guessIdx++) {
if( found[guessIdx] != 1 )
for(int answerIdx = 0; answerIdx < CNT; answerIdx++) {
if( found[answerIdx] == 0 && (guess[guessIdx] == answer[answerIdx]) && guessIdx != answerIdx ) {
b[idx]++;
found[answerIdx] = 2;
break;
}
}
}
idx++;
}
idx = 0;
while( idx < round ) {
printf("%dA%dB\n", a[idx], b[idx]);
idx++;
}
}
return 0;
}
沒有留言:
張貼留言