HDU 1045 - Fire Net (最大獨立集)

來源:互聯網
上載者:User

標籤:style   blog   class   code   tar   color   int   string   art   http   set   

題意:給你一個正方形棋盤。每個棋子可以直線攻擊,除非隔著石頭。現在要求所有棋子都不互相攻擊,問最多可以放多少個棋子。

 

這個題可以用搜尋來做。每個棋子考慮放與不放兩種情況,然後再判斷是否能互相攻擊來剪枝。最後取可以放置的最大值。

這裡我轉化成求最大獨立集來做。

首先將每個空地編號,對於每個空地,與該位置可以攻擊到的空地連邊。找最多的空地使得不互相攻擊,即求該圖的最大獨立集。與搜尋做法基本一致,但是說法略有不同。

 1 #include<iostream> 2 #include<cstring> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstdlib> 6 #include<cstdio> 7 #include<vector> 8 using namespace std; 9 char grid[5][5];10 bool gl[30][30];11 int g[5][5];12 int n,cn,ans;13 bool col[30];14 void init()15 {16     memset(gl,0,sizeof(gl));17     cn=0;18     for(int i=0; i<n; ++i)19         for(int j=0; j<n; ++j)20             if(grid[i][j]==‘.‘)21                 g[i][j]=++cn;22             else g[i][j]=0;23     for(int i=0; i<n; ++i)24         for(int j=0; j<n; ++j)25             if(grid[i][j]==‘.‘)26             {27                 int &now=g[i][j];28                 for(int k=j+1; k<n&&g[i][k]; ++k)29                     gl[now][g[i][k]]=true;30                 for(int k=j-1; k>=0&&g[i][k]; --k)31                     gl[now][g[i][k]]=true;32                 for(int k=i+1; k<n&&g[k][j]; ++k)33                     gl[now][g[k][j]]=true;34                 for(int k=i-1; k>=0&&g[k][j]; --k)35                     gl[now][g[k][j]]=true;36             }37     ans=0;38     memset(col,0,sizeof(col));39 40 }41 void dfs(int d,int res)42 {43     if(d>cn) ans=max(ans,res);44     else45     {46         bool ok=true;47         for(int i=1; i<=cn; ++i)48             if(gl[d][i]&&col[i]) ok=false;49         if(ok)50         {51             col[d]=true;52             dfs(d+1,res+1);53             col[d]=false;54         }55         dfs(d+1,res);56     }57 }58 int main()59 {60     while(scanf("%d",&n)!=EOF&&n)61     {62         for(int i=0; i<n; ++i)63             scanf("%s",grid[i]);64         init();65         dfs(1,0);66         printf("%d\n",ans);67     }68     return 0;69 }
View Code

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.