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 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(ij) is negative, then Alice gives |M(ij)| 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 (1 ≤ ≤ 20), the number of test cases. Each test case starts with (1 ≤ ≤ 8), the size of the grid. Then follow lines containing nnumbers separated by spaces describing M. We call the jth number on ith line M(ij) (-1000 ≤M(ij)≤ 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

题目大意:Alice和bob两个傻逼又开始玩游戏了,一个人划掉行,一个人划掉一列,为了阻止winner,使他分数最小,求解

比八皇后问题还简单,把皇后问题还要划掉斜线呢,所以一个回溯解决,1遍AC,没有坑点


#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;
} 




posted @ 2013-08-26 10:19  炒饭君  阅读(404)  评论(0编辑  收藏  举报