题意:如果一个对称矩阵,对角线元素均为0,且 aij = aji,aii = 0 , aij ≤ max(aik, ajk) for all triples i, j, k. ,则这个矩阵Magic,给一个n*n( n≤2500 )矩阵问其是否Magic?
考虑 ai,j≤max(aik,akj) ,如果考虑建一个点数为n的完全图,此条件等价为——这张图的任一生成树必为最小生成树
所以只要在MST加边的时候,如果加的边长度增加,则此时图中所有连通块必为完全图(否则少的那条边必不取)
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<iostream>
#include<cmath>
#include<cctype>
#include<ctime>
#include<iomanip>
using namespace std;
#define For(i,n) for(int i=1;i<=n;i++)
#define Fork(i,k,n) for(int i=k;i<=n;i++)
#define Rep(i,n) for(int i=0;i<n;i++)
#define ForD(i,n) for(int i=n;i;i--)
#define RepD(i,n) for(int i=n;i>=0;i--)
#define Forp(x) for(int p=pre[x];p;p=next[p])
#define Forpiter(x) for(int &p=iter[x];p;p=next[p])
#define Lson (x<<1)
#define Rson ((x<<1)+1)
#define MEM(a) memset(a,0,sizeof(a));
#define MEMI(a) memset(a,127,sizeof(a));
#define MEMi(a) memset(a,128,sizeof(a));
#define INF (2139062143)
#define F (100000007)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define vi vector<int>
typedef long long ll;
ll mul(ll a,ll b){return (a*b)%F;}
ll add(ll a,ll b){return (a+b)%F;}
ll sub(ll a,ll b){return (a-b+llabs(a-b)/F*F+F)%F;}
void upd(ll &a,ll b){a=(a%F+b%F)%F;}
int read()
{
int x=0,f=1; char ch=getchar();
while(!isdigit(ch)) {if (ch=='-') f=-1; ch=getchar();}
while(isdigit(ch)) { x=x*10+ch-'0'; ch=getchar();}
return x*f;
}
#define MAXN (2500+10)
int n;
ll a[MAXN][MAXN];
pair<int,pair<int,int> > v[MAXN*MAXN];
class bingchaji
{
public:
int father[MAXN],rk[MAXN],cnt[MAXN],n;
void mem(int _n)
{
n=_n;
For(i,n) father[i]=i,rk[i]=1,cnt[i]=0;
}
int getfather(int x)
{
if (father[x]==x) return x;
return father[x]=getfather(father[x]);
}
void unite(int x,int y)
{
father[x]=getfather(father[x]);
father[y]=getfather(father[y]);
x=father[x],y=father[y];
if (x==y) cnt[x]++;
else {
father[y]=x;
rk[x]+=rk[y];
cnt[x]+=cnt[y]+1;
}
}
bool same(int x,int y)
{
return getfather(x)==getfather(y);
}
}S;
bool check() {
int m=0;
For(i,n) For(j,i-1) {
if (a[i][j]!=a[j][i]) return 0;
v[++m]=mp(a[i][j],mp(i,j));
}
For(i,n) if (a[i][i]) return 0;
sort(v+1,v+1+m);
S.mem(n);
int t=0;
For(i,m) {
if (i==1 || v[i].fi!=v[i-1].fi) {
if (++t>n) return 0;
For(j,n) if (S.father[j]==j &&S.rk[j]*(S.rk[j]-1)/2!=S.cnt[j])
return 0;
}
S.unite(v[i].se.fi,v[i].se.se);
}
return 1;
}
int main()
{
// freopen("CF632F.in","r",stdin);
// freopen(".out","w",stdout);
scanf("%d",&n);
For(i,n) For(j,n) a[i][j]=read();
if (check()) puts("MAGIC");
else puts("NOT MAGIC");
return 0;
}