uva 140 bandwidth (好题) ——yhx

 Bandwidth 

Given a graph (V,E) where V is a set of nodes and E is a set of arcs in VxV, and an ordering on the elements in V, then the bandwidth of a node v is defined as the maximum distance in the ordering between v and any node to which it is connected in the graph. The bandwidth of the ordering is then defined as the maximum of the individual bandwidths. For example, consider the following graph:

uva 140 bandwidth (好题) ——yhx

This can be ordered in many ways, two of which are illustrated below:

uva 140 bandwidth (好题) ——yhx

For these orderings, the bandwidths of the nodes (in order) are 6, 6, 1, 4, 1, 1, 6, 6 giving an ordering bandwidth of 6, and 5, 3, 1, 4, 3, 5, 1, 4 giving an ordering bandwidth of 5.

Write a program that will find the ordering of a graph that minimises the bandwidth.

Input

Input will consist of a series of graphs. Each graph will appear on a line by itself. The entire file will be terminated by a line consisting of a single #. For each graph, the input will consist of a series of records separated by `;'. Each record will consist of a node name (a single upper case character in the the range `A' to `Z'), followed by a `:' and at least one of its neighbours. The graph will contain no more than 8 nodes.

Output

Output will consist of one line for each graph, listing the ordering of the nodes followed by an arrow (->) and the bandwidth for that ordering. All items must be separated from their neighbours by exactly one space. If more than one ordering produces the same bandwidth, then choose the smallest in lexicographic ordering, that is the one that would appear first in an alphabetic listing.

 #include<cstdio>
#include<cstring>
bool use[],app[];
int map[][],n,a[],ans,ans_arr[],alfa[];
void dfs(int fin,int cur)
{
int i,j,k,p,q,x,y,z,cnt,temp;
char c1,c2;
if (cur>=ans) return;
cnt=;
for (i=;i<=n;i++)
if (map[alfa[a[fin]]][alfa[i]]&&!use[i]) cnt++;
if (cnt>=ans) return;
if (fin==n)
{
ans=cur;
for (i=;i<=n;i++)
ans_arr[i]=a[i];
return;
}
fin++;
for (i=;i<=n;i++)
if (!use[i])
{
a[fin]=i;
temp=cur;
use[i]=;
for (j=;j<fin-cur;j++)
if (map[alfa[i]][alfa[a[j]]])
{
temp=fin-j;
break;
}
dfs(fin,temp);
use[i]=;
}
}
int main()
{
char s[],c;
int i,x,y;
while (scanf("%s",s)&&s[]!='#')
{
memset(map,,sizeof(map));
memset(use,,sizeof(use));
memset(a,,sizeof(a));
memset(alfa,,sizeof(alfa));
memset(app,,sizeof(app));
n=;
for (i=;i<strlen(s);)
{
c=s[i++];
x=c-'A'+;
app[x]=;
i++;
while (s[i]!=';'&&i<strlen(s))
{
y=s[i]-'A'+;
app[y]=;
map[x][y]=map[y][x]=;
i++;
}
i++;
}
for (i=;i<=;i++)
if (app[i])
alfa[++n]=i;
ans=0x3f3f3f3f;
dfs(,);
for (i=;i<=n;i++)
printf("%c ",alfa[ans_arr[i]]+'A'-);
printf("-> %d\n",ans);
}
}

搜索+剪枝。

1.目前带宽大于等于已知答案,剪枝。

2.在搜索到某一节点时,与该节点连接的还没有加入排列的点的个数大于等于已知答案,剪枝。(若这些点全都紧跟在此点之后,带宽也为其个数。否则更大。)

读入数据处理的时候注意,要让字母序小的排在前头。

注意各种下标、字母、数字、位置的变量引用。

上一篇:(32位)本体学习程序(ontoEnrich)系统使用说明文档


下一篇:animate.css总结