UVa 10336 - Rank the Languages ( DFS )

题意

各国语言统计, 类似连通块, 但只有上下左右四个方向, 斜对角不算连通
最后按照语言使用人数按照从大到小排序输出, 人数相等的按照字典序输出

思路

只走上下左右四个方向的DFS连通块 用一个abs就能巧妙转化

for( int dx = -1; dx <= 1; dx++ ){
        for( int dy = -1; dy <= 1; dy++ ){
            if( abs(dx+dy) != 1 )   continue;
        }
}

用结构体存下语言代号及人数, 用结构体排序即可

bool cmp( struct MAP a, struct MAP b )
{
    if( a.x == b.x )
        return a.c < b.c;
    return a.x > b.x;
}

AC代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>

using namespace std;
int m, n;
int alp[30];
char mrk[30];
char s[50][50];

struct MAP{
    char c;
    int x;
};
struct MAP p[30];

bool cmp( struct MAP a, struct MAP b )
{
    if( a.x == b.x )
        return a.c < b.c;
    return a.x > b.x;
}

void dfs( int x, int y, char a )
{
    s[x][y] = '0';
    for( int dx = -1; dx <= 1; dx++ ){
        for( int dy = -1; dy <= 1; dy++ ){
            if( abs(dx+dy) != 1 )   continue;
            int nx = x + dx, ny = y + dy;
            if( nx >= 0 && nx < m && ny >= 0 && ny < n && s[nx][ny] == a )
                dfs( nx, ny, a );
        }
    }
    return;
}

void solve( char a, int k )
{
    int num = 0;
    for( int i = 0; i < m; i++ ){
        for( int j = 0; j < n; j++ ){
            if( s[i][j] == a ){
                dfs(i,j,a);
                num++;
            }
        }
    }
    p[k].c = a, p[k].x = num;
}

int main()
{
    int T, kase = 0;
    scanf("%d",&T);
    while(T--){
        int num = 0;
        memset(s,0,sizeof(s));
        memset(alp,0,sizeof(alp));
        memset(mrk,0,sizeof(mrk));
        scanf("%d%d",&m,&n);
        getchar();
        for( int i = 0; i < m; i++ ){
            for( int j = 0; j < n; j++ ){
                scanf("%c",&s[i][j]);
                if( !alp[s[i][j] - 'a'] ){
                    alp[s[i][j] - 'a'] = 1;
                    mrk[num] = s[i][j];
                    num++;
                }
            }
            getchar();
        }
        printf("World #%d\n",++kase);
        for( int i = 0; i < num; i++ )
            solve( mrk[i], i );
        sort( p, p+num, cmp );
        for( int i = 0; i < num; i++ )
            printf("%c: %d\n",p[i].c, p[i].x);
    }
    return 0;
}

转载于:https://www.cnblogs.com/JinxiSui/p/9740601.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值