题意:给你一些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;
}