uva 11553 Grid Game (回溯- 类似,比八皇后问题简单)
uva 11553 Grid Game (回溯- 类似,比八皇后问题简单)
Problem G
GRID GAME
Alice and Bob both have lots of candies but want more. They decide to play the following turn-based game.
They fill an n x n grid M with random integers. Alice begins the game by crossing off an uncrossed row i of the grid. Now it’s Bob turn and he crosses off an uncrossed column j of the grid. At the end of Bob’s turn, Alice takes the number candies in the ith row and jth column ofM, call this value M(i, j), from Bob. (If M(i, j) is negative, then Alice gives |M(i, j)| candies to Bob.) The game continues alternating turns from Alice to Bob until the entire board is crossed off.
What is the largest amount of candies that Alice can win from Bob (or least amount to lose if she cannot win) if both Alice and Bob play optimally?
The beginning of a game between Alice (red) and Bob (blue).
Program Input
The first line of the input contains an integer t (1 ≤ t ≤ 20), the number of test cases. Each test case starts with n (1 ≤ n ≤ 8), the size of the grid. Then follow n lines containing nnumbers separated by spaces describing M. We call the jth number on ith line M(i, j) (-1000 ≤M(i, j)≤ 1000).
Program Output
For each test case, print the largest amount of candies that Alice can win from Bob. If she cannot win, print the negative number indicating the minimum number of candies she loses.
Sample Input & Output
INPUT
3
2
10 10
-5 -5
2
10 -5
10 -5
2
10 -5
-5 10
OUTPUT
5 5 -10
Calgary Collegiate Programming Contest 2008
#include <iostream> #include <cstdio> using namespace std; const int maxn=10; int t,n,a[maxn][maxn],visited[maxn][maxn],marked,ans; void initial(){ for(int i=0;i<maxn;i++) for(int j=0;j<maxn;j++) visited[i][j]=0; marked=1; ans=20000000; } void input(){ scanf("%d",&n); for(int i=0;i<n;i++) for(int j=0;j<n;j++) scanf("%d",&a[i][j]); } void backtracking(int r,int sum){ if(r>=n){ if(sum<ans) ans=sum; return; } for(int c=0;c<n;c++){ if(!visited[r][c]){ for(int i=r;i<n;i++) visited[i][c]++; backtracking(r+1,sum+a[r][c]); for(int i=r;i<n;i++) visited[i][c]--; } } } void computing(){ backtracking(0,0); cout<<ans<<endl; } int main(){ cin>>t; while(t-- >0){ initial(); input(); computing(); } return 0; }