poj1021

来源:互联网 发布:淘宝店多少销量能靠前 编辑:程序博客网 时间:2024/05/17 23:28

题目描述:判断两个图是否等价。
对等价的定义是:两个图有相同个数的连通块,第一个图里面的每个连通块总能在第二个图里面找到一个连通块(未与别的块匹配)与之匹配。
对连通块匹配的定义是:两个连通块如果能经过若干次平移、对称、旋转等操作之后重合,则说它们是匹配的。
现在要求设计程序,输入两个图,输出它们是否等价。
输入格式:第一行一个整数t,表示有t组数据,接下来t组数据,每组数据由3行构成,第一行三个整数w,h,n,分别表示图的宽度,高度,和点的数量。接下来两行,表示两个图的点,每行n对整数,分别表示n个点的x和y。
输出格式:每组数据输出一个YES或者NO。
解题思路:找出两个图的所有连通块,对每个连通块进行hash,hash值是连通块里面所有点两两之间距离的平方和。然后将连通块按hash值排序。判断是否有不匹配的连通块。
具体的在代码里面:

#include <cstdio>#include <algorithm>#define MAXN 111using namespace std;void inputmap(int n, bool map[][MAXN]);void solve(bool map[][MAXN], int w, int h, int *st, int &top);int main(int argc, char const *argv[]){    int t;    for(scanf("%d", &t); t; --t){        bool map1[MAXN][MAXN]={false};        bool map2[MAXN][MAXN]={false};        //start of getting in         int W, H, n;        scanf("%d%d%d", &W, &H, &n);        inputmap(n, map1);        inputmap(n, map2);        //end of getting in        int top1=0, top2=0;        int st1[MAXN*MAXN];        int st2[MAXN*MAXN];        //start of solving        solve(map1, W, H, st1, top1);        solve(map2, W, H, st2, top2);               //end of solving        //begin of output answer        bool flag=false;        if(top1==top2){            flag=true;            int top=top1;            sort(st1,st1+top);            sort(st2,st2+top);            for(int i=0; i<top; ++i){                if(st1[i]!=st2[i]){                    flag=false;                    break;                }            }        }        if(flag){ printf("YES\n"); }        else { printf("NO\n"); }        //end of output answer    }    return 0;}void inputmap(int n, bool map[][MAXN]){    for(int i=0; i<n; ++i){        int x, y;        scanf("%d%d", &x, &y);        map[x][y]=true;    }}void solve(bool map[][MAXN], int w, int h, int *st, int &top){    bool vis[MAXN][MAXN]={false};    for(int i=0; i<w; ++i){        for(int j=0; j<h; ++j){            if(!map[i][j] || vis[i][j]) { continue; }            vis[i][j]=true;            int head=0, tail=1;            int qx[MAXN]={i}, qy[MAXN]={j};            while(head!=tail){                int x=qx[head], y=qy[head]; ++head;                const int xx[4]={-1,0,1,0};                const int yy[4]={0,-1,0,1};                for(int i=0; i<4; ++i){                    int dx=x+xx[i], dy=y+yy[i];                    if(dx<0 || dx>=w || dy<0 || dy>=h) { continue; }                    if(!map[dx][dy] || vis[dx][dy]) { continue; }                    qx[tail]=dx; qy[tail]=dy; ++tail;                    vis[dx][dy]=true;                }            }            int hash=0;            for(int i=0; i<tail; ++i){                for(int j=i+1; j<tail; ++j){                    int x=qx[i]-qx[j];                    int y=qy[i]-qy[j];                    hash += x*x+y*y;                }            }            st[top++]=hash;        }    }}
0 0
原创粉丝点击