SGU101 DFS

    题意:给你一些Domino,两端有数字,问能否用全部骨牌首尾相连成一条链,使得相连的两端数字相同。可以的话要给出方案。

    Problem:Give you some dominoes which have numbers on it's both sides. Can you connect the dominoes one by one to form a chain? It requires the dominoes touch through equal marked sides. If there exist any solution, you should give one.

    解法:先算出现次数,显然出现奇数次的牌必须是0个或2个。之后DFS,使得每个牌都用上。最后再根据DFS顺序得到方案。

    Solution:First calculate the times that these numbers appeared. Apparently, the number of dominoes which appear odd times must be 0 or 2.  Then DFS to make every domino to be used. Finally, you make the solution according to the DFS result.

    

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
struct data {
       int x,y;
}g[1000],ans[1000];
int x[10],a[10][10],n,cnt,s,b,c;
void dfs(int x) {
     for (int i=0;i<=6;i++)
         if (a[x][i]) {
            a[x][i]--;
            a[i][x]--;
            dfs(i);
            cnt++;
            ans[cnt].x = x;
            ans[cnt].y = i;
         }
}
int main() {
    while (~scanf("%d",&n)) {
          memset(a,0,sizeof(a));
          memset(x,0,sizeof(x));
          for (int i=1;i<=n;i++) {
              scanf("%d%d",&b,&c);
              a[b][c]++;
              a[c][b]++;
              x[b]++;
              x[c]++;
              g[i].x = b;
              g[i].y = c;
          }
          cnt = 0, s = -1;
          for (int i=0;i<=6;i++) {
              if (x[i]%2==1) {
                 cnt++;
                 s = i;
              }
              else if (x[i] && s==-1) s = i;
          }
          if (cnt==1 || cnt>2) {
             printf("No solution\n");
             continue;
          }
          cnt = 0;
          dfs(s);
          if (cnt<n) {
             printf("No solution\n");
             continue;
          }
          for (int i=cnt;i>=1;i--)
              for (int j=1;j<=n;j++)
                  if (ans[i].x==g[j].x && ans[i].y==g[j].y) {
                     printf("%d +\n",j);
                     g[j].x = -1;
                     break;
                  }
                  else if (ans[i].x==g[j].y && ans[i].y==g[j].x) {
                     printf("%d -\n",j);
                     g[j].x = -1;
                     break;
                  }
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值