zoukankan      html  css  js  c++  java
  • 洛谷 P1123 取数游戏

    题目描述

    一个N×M的由非负整数构成的数字矩阵,你需要在其中取出若干个数字,使得取出的任意两个数字不相邻(若一个数字在另外一个数字相邻8个格子中的一个即认为这两个数字相邻),求取出数字和最大是多少。

    输入输出格式

    输入格式:

     

    输入第1行有一个正整数T,表示了有T组数据。

    对于每一组数据,第1行有两个正整数N和M,表示了数字矩阵为N行M列。

    接下来N行,每行M个非负整数,描述了这个数字矩阵。

     

    输出格式:

     

    输出包含T行,每行一个非负整数,输出所求得的答案。

     

    输入输出样例

    输入样例#1: 复制
    3
    4 4
    67 75 63 10
    29 29 92 14
    21 68 71 56
    8 67 91 25
    2 3
    87 70 85
    10 3 17
    3 3
    1 1 1
    1 99 1
    1 1 1
    
    
    输出样例#1: 复制
    271
    172
    99
    

    说明

    对于第1组数据,取数方式如下:

    [67] 75 63 10

    29 29 [92] 14

    [21] 68 71 56

    8 67 [91] 25

    对于20%的数据,N, M≤3;

    对于40%的数据,N, M≤4;

    对于60%的数据,N, M≤5;

    对于100%的数据,N, M≤6,T≤20。

    思路:搜索。

    #include<cstring>
    #include<cstdio>
    int t,n,m,ans;
    int a[15][15];
    int can[15][15];
    int dx[9]={1,1,1,0,0,-1,-1,-1};
    int dy[9]={1,-1,0,-1,1,0,1,-1};
    void dfs(int i,int j,int now){
        if(j>m){ i++;j=1; } 
        if(i>n){ if(now>ans)ans=now;return; }
        if(can[i][j]==0){
            for(int k=0;k<8;k++)    can[i+dx[k]][j+dy[k]]++;
            dfs(i,j+2,now+a[i][j]);
            for(int k=0;k<8;k++)    can[i+dx[k]][j+dy[k]]--;
        }
        dfs(i,j+1,now);
    }
    int main(){
        scanf("%d",&t);
        while(t--){
            ans=0;
            scanf("%d%d",&n,&m);
            for(int i=1;i<=n;i++)
                for(int j=1;j<=m;j++)
                    scanf("%d",&a[i][j]); 
            memset(can,0,sizeof(can));
            dfs(1,1,0);
            printf("%d
    ",ans);
        }
    }
    细雨斜风作晓寒。淡烟疏柳媚晴滩。入淮清洛渐漫漫。 雪沫乳花浮午盏,蓼茸蒿笋试春盘。人间有味是清欢。
  • 相关阅读:
    LeetCode "Super Ugly Number" !
    LeetCode "Count of Smaller Number After Self"
    LeetCode "Binary Tree Vertical Order"
    LeetCode "Sparse Matrix Multiplication"
    LeetCode "Minimum Height Tree" !!
    HackerRank "The Indian Job"
    HackerRank "Poisonous Plants"
    HackerRank "Kundu and Tree" !!
    LeetCode "Best Time to Buy and Sell Stock with Cooldown" !
    HackerRank "AND xor OR"
  • 原文地址:https://www.cnblogs.com/cangT-Tlan/p/8000989.html
Copyright © 2011-2022 走看看