[ssl 1344] Knights

题目

Description
  We are given a chess-board of size n*n, from which some fields have been removed. The task is to determine the maximum number of knights that can be placed on the remaining fields of the board in such a way that none of them check each other.
  一张大小为n*n的国际象棋棋盘,上面有一些格子被拿走了,棋盘规模n不超过200。马的攻击方向如下图,其中S处为马位置,标有X的点为该马的攻击点。
Fig.1: A knight placed on the field S checks fields marked with x.
Write a program, that:
reads the description of a chess-board with some fields removed, from the input file kni.in,
determines the maximum number of knights that can be placed on the chess-board in such a way that none of them check each other,
writes the result to the output file kni.out.
你的任务是确定在这个棋盘上放置尽可能多的马,并使他们不互相攻击。
Input
The first line of the input file kni.in contains two integers n and m, separated by a single space, 1<=n<=200, 0<=m<n2; n is the chess-board size and m is the number of removed fields. Each of the following m lines contains two integers: x and y, separated by a single space, 1<=x,y<=n – these are the coordinates of the removed fields. The coordinates of the upper left corner of the board are (1,1), and of the bottom right are (n,n). The removed fields are not repeated in the file.
Output
The output file kni.out should contain one integer (in the first and only line of the file). It should be the maximum number of knights that can be placed on the given chess-board without checking each other.
Sample Input
3 2
1 1
3 3

Sample Output
5

解题思路

> 求最大独立集: 给定一个二分图,要求选出点集G,使得G中任意两顶点不连通,即无边相连,且G中顶点数最多。
> 定理:U=V-M;V=顶点数,M=最大匹配数(最小覆盖数),U=最大独立集。

代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int b[8]={-2,-1,1,2,2,1,-1,-2},c[8]={1,2,2,1,-1,-2,-2,-1};
struct node{
    int y,next; 
}a[400000]; 
int rr,ans,sum,add,n,m,xx,yy,link[40001],v[40001],list[40001],t[201][201];
bool find (int q){
    for (int i=list[q];i;i=a[i].next)
      if (!v[a[i].y])
      {
            v[a[i].y]=1; 
            int u=link[a[i].y]; 
            link[a[i].y]=q; 
            if (!u||find(u)) return true; 
            link[a[i].y]=u; 
      } 
    return false;
}
int main()
{
    scanf("%d%d",&n,&m); 
    for (int i=1;i<=m;i++)
     scanf("%d%d",&xx,&yy),t[xx][yy]=-1; 
     ans=n*n-m; 
    for (int i=1;i<=n;i++)
     for (int j=1;j<=n;j++)
     if (!t[i][j]&&(i+j)%2)
     {
        t[i][j]=++add;
        for (int k=0;k<8;k++)
         {
           xx=i+b[k]; 
           yy=j+c[k];
           if ((xx>=1&&xx<=n)&&(yy>=1&&yy<=n))
           {
             if (!t[xx][yy]) 
                t[xx][yy]=++rr; 
             if (t[xx][yy]!=-1){
                a[++sum].y=t[xx][yy]; 
                a[sum].next=list[add]; 
                list[add]=sum; 
             }
           }
        }
     }
   for (int i=1;i<=add;i++)
   {
        memset(v,0,sizeof(v));
        if (find(i)) ans--; 
   }
   printf("%d",ans); 
}

猜你喜欢

转载自blog.csdn.net/qq_39897867/article/details/80029542
SSL
今日推荐