Poj--1681(数学,高斯消元)

2014-09-17 00:29:08

思路:和poj1222很像,建立n×n个方程,高斯消元即可,注意还要判断无解的情况。(一开始不会判无解Wrong了一发,QAQ)

 1 /*************************************************************************
 2 
 3     > File Name: 1681.cpp
 4     > Author: Nature
 5     > Mail: 564374850@qq.com 
 6     > Created Time: Tue 16 Sep 2014 05:35:36 PM CST
 7 ************************************************************************/
 8 
 9 #include <cstdio>
10 #include <cstring>
11 #include <cstdlib>
12 #include <cmath>
13 #include <vector>
14 #include <queue>
15 #include <iostream>
16 #include <algorithm>
17 using namespace std;
18 typedef long long ll;
19 const int INF = 1 << 29;
20 typedef int Matrix[300][300];
21 
22 int t,n,top;
23 Matrix A;
24 
25 int Gauss(){
26     int equ,var,col = 0,i,j,k,r;
27     equ = var = top;
28     for(i = 0; i < equ && col < var; ++i,++col){
29         r = i;
30         for(j = i + 1; j < equ; ++j) if(A[j][col]){
31             r = j;
32             break;
33         }
34         if(r != i)
35             for(j = col; j <= var; ++j) swap(A[i][j],A[r][j]);
36         if(A[i][col] == 0){
37             --i;
38             continue;
39         }
40         for(k = i + 1; k < equ; ++k){
41             if(A[k][col]){
42                 for(j = 0; j <= var; ++j)
43                     A[k][j] ^= A[i][j];
44             }
45         }
46     }
47     for(; i < equ; ++i){
48         if(A[i][col] != 0)
49             return 0;
50     }
51     for(i = equ - 1; i >= 0; --i){
52         for(j = i + 1; j < equ; ++j)
53             A[i][var] ^= (A[i][j] && A[j][var]);
54     }
55     return 1;
56 }
57 
58 void Init(){
59     memset(A,0,sizeof(A));
60     for(int i = 0; i < top; ++i){
61         A[i][i] = 1;
62         if(i >= n) A[i][i - n] = 1; //up
63         if(i + n < top) A[i][i + n] = 1; //down
64         if(i % n != 0) A[i][i - 1] = 1; //left
65         if((i + 1) % n != 0) A[i][i + 1] = 1; //right
66     }
67 }
68 
69 int main(){
70     char str[20];
71     scanf("%d",&t);
72     while(t--){
73         scanf("%d",&n);
74         top = n*n;
75         Init();
76         for(int i = 0; i < n; ++i){
77             scanf("%s",str);
78             for(int j = 0; j < n; ++j)
79                 A[i*n + j][top] = (str[j] == 'y' ? 0 : 1);
80         }
81         if(Gauss()){
82             int cnt = 0;
83             for(int i = 0; i < top; ++i) if(A[i][top]) ++cnt;
84             printf("%d\n",cnt);
85         }
86         else printf("inf\n");
87     }
88     return 0;
89 }

 

posted @ 2014-09-17 00:30  Naturain  阅读(155)  评论(0)    收藏  举报