poj The Clocks 高斯消元

由于数据量不大,所以这题有很多解法。

我用的是高斯消元化为逆矩阵解决的……

代码如下:

#include<stdio.h>
#include<iostream>
using namespace std;
int an[9][10]={
{1,1,0,1,0,0,0,0,0,0},
{1,1,1,0,1,0,0,0,0,0},
{0,1,1,0,0,1,0,0,0,0},
{1,0,0,1,1,0,1,0,0,0},
{1,0,1,0,1,0,1,0,1,0},
{0,0,1,0,1,1,0,0,1,0},
{0,0,0,1,0,0,1,1,0,0},
{0,0,0,0,1,0,1,1,1,0},
{0,0,0,0,0,1,0,1,1,0}
},ans[9];
int main(){
    int n,i,j,k,sum,ma,mb;
    for(i=0;i<9;i++){
        cin>>an[i][9];
        an[i][9]=(4-an[i][9])%4;
    }
    for(i=0;i<9;i++){
        if(an[i][i]==0){
            for(k=i+1;k<9;k++){
                if(an[k][i]){
                    for(j=0;j<=9;j++)
                        swap(an[i][j],an[k][j]);
                    break;
                }
            }
        }
        for(k=i+1;k<9;k++){
            if(an[k][i]){
                ma=an[i][i];
                mb=an[k][i];
                for(j=i;j<=9;j++){
                    an[k][j]=ma*an[k][j]-mb*an[i][j];
                    an[k][j]=(an[k][j]%4+4)%4;
                }
            }
        }
    }
    sum=0;
    for(i=8;i>=0;i--){
        for(j=i+1;j<9;j++){
            an[i][9]-=ans[j]*an[i][j];
            an[i][9]=(an[i][9]%4+4)%4;
        }
        for(ans[i]=0;ans[i]<=3;ans[i]++)
            if((ans[i]*an[i][i]%4+4)%4==an[i][9])
                break;
        ans[i]%=4;
        sum+=ans[i];
    }
    j=0;k=0;
    while(j<9){
        if(ans[j]){
            cout<<j+1;
            k++;
            if(k>=sum) cout<<endl;
            else cout<<' ';
            ans[j]--;
        }
        else j++;
    }
    return 0;
}
View Code

 

posted @ 2013-08-02 15:15  _随心所欲_  阅读(299)  评论(0编辑  收藏  举报