有些內容使用中英雙語,有些只有英文或中文。歡迎使用與分享任何內容,但先來信告知並標示此部落格為出處。
Some parts use both Chinese and English, but some parts use only one language. Feel free to share, but please contact me first and list this blog as your reference.

2014年2月11日 星期二

UVa OJ - 10164 Number Game

The following program is my ACcepted code for UVA-10164.
It's a for everybody to learn and discuss.
If there is any mistake or comment, please let me know.  :D

此乃UAV 10164 的AC code!
歡迎一同討論學習,如有錯誤與任何建議請留言 : )

//This program is for UVA 10164 Number Game
//http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1105
#include<stdio.h>//input and output
#include<stdlib.h>
#include<string.h>//for the memset function
#define MAX 2500
using namespace std;
int N;//the N
int n[MAX];//array for all the number, 2^10 = 1024, 2*(2^10) = 2048
int len;//this is from the 2*N-1
int ans[MAX];//array for saving the answers
bool findAns;
/*
/um is the current sum of numbers
count is the current number of answers
now is the current index of n (array).
*/
void backtrack(int sum, int count, int now)
{
/* print data for checking!
if(count >1){
printf("out: %3d %3d %3d %d ", sum, count, now, sum%N);//for the test
for(int i = 0; i < count-1; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[count-1]);
}
else if(count == 1)
{
printf("out: %3d %3d %3d %d ", sum, count, now, sum%N);//for the test
printf("%d \n", ans[0]);
}*/
if(findAns)//once find one of the answers, then return to end this function
return;
if(now > len)
return;
if(count > N)//choose more than N numbers so end this way
return;
if(count == N && sum % N == 0)
{
//printf("in: %3d %3d %3d %d\n", sum, count, now, sum%N);//print answer for checking
findAns = true;
printf("Yes\n");
for(int i = 0; i < N-1; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[N-1]);
return;
}
ans[count] = n[now];//answer saved as array n with indes now, and then
backtrack(sum + n[now], count + 1, now + 1);
backtrack(sum, count, now + 1);
return;
}
int main()
{
while(scanf("%d", &N)!=EOF)
{
if(N == 0)
break;
memset(n, 0, sizeof(n));
memset(ans, 0, sizeof(ans));
len = 2 * N - 1;
for(int i=0;i < len; i++)
scanf("%d", &n[i]);
findAns = false;
backtrack(0, 0, 0);
if(!findAns)
printf("No\n");
}
return 0;
}
Please feel free to use it after adding this blog as an reference. (http://autekroy.blogspot.tw) If there is any mistake or comment, please let me know. :D 

歡迎使用與分享任何內容,但請記得標示此部落格為出處。(http://autekroy.blogspot.tw/) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )

沒有留言:

張貼留言

請留下您的任何想法或建議!
Please leave any thought or comment!