codeforces 711B B. Chris and Magic Square(水题)

题目链接:

B. Chris and Magic Square

题意:

问在那个空位子填哪个数可以使行列对角线的和相等,就先找一行或者一列算出那个数,再验证是否可行就好;

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <bits/stdc++.h>
#include <stack>
#include <map>
 
using namespace std;
 
#define For(i,j,n) for(int i=j;i<=n;i++)
#define mst(ss,b) memset(ss,b,sizeof(ss));
 
typedef  long long LL;
 
template<class T> void read(T&num) {
    char CH; bool F=false;
    for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar());
    for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar());
    F && (num=-num);
}
int stk[70], tp;
template<class T> inline void print(T p) {
    if(!p) { puts("0"); return; }
    while(p) stk[++ tp] = p%10, p/=10;
    while(tp) putchar(stk[tp--] + '0');
    putchar('\n');
}
 
const LL mod=1e9+7;
const double PI=acos(-1.0);
const int inf=1e9;
const int N=4e5+10;
const int maxn=1e3+520;
const double eps=1e-12;

LL mp[505][505],l[505],r[505];
int main()
{
    int n,x=0,y=0;
    read(n);
    For(i,1,n)
    {
        r[i]=0;
        For(j,1,n)
        {
            read(mp[i][j]);
            if(mp[i][j]==0)
            {
                x=i;y=j;
            }
            r[i]+=mp[i][j];
        }
    }
    if(n==1)
    {
        cout<<"1\n";
        return 0;
    }
    int num=0;
    for(int i=2;i<=n;i++)
    {
        if(r[i]!=r[i-1])num++;
    }
    if(num>2)cout<<"-1\n";
    else 
    {
        LL temp;
        if(x>1)temp=r[1];
        else temp=r[2];
        LL sum=temp;
        for(int i=1;i<=n;i++)
        {
            if(mp[x][i])temp-=mp[x][i];
        }
        mp[x][y]=temp;
        if(temp<=0)cout<<"-1\n";
        else 
        {
            for(int i=1;i<=n;i++)
            {
                l[i]=0;
                for(int j=1;j<=n;j++)
                {
                    l[i]+=mp[j][i];
                }
            }
            for(int i=2;i<=n;i++)
            {
                if(l[i]!=sum)
                {
                    cout<<"-1\n";
                    return 0;
                }
            }
            temp=0;
            for(int i=1;i<=n;i++)
            {
                temp+=mp[i][i];
            }
            if(temp!=sum)
            {
                cout<<"-1\n";
                return 0;
            }
            temp=0;
            for(int i=1;i<=n;i++)
            {
                temp+=mp[i][n-i+1];
            }
            if(temp!=sum)
            {
                cout<<"-1\n";
                return 0;
            }
            cout<<mp[x][y]<<endl;
        }
    }

    return 0;
}

  

posted @ 2016-08-30 09:41  LittlePointer  阅读(189)  评论(0编辑  收藏  举报