Bandwidth
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:
This can be ordered in many ways, two of which are illustrated below:
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.
Sample input
A:FB;B:GC;D:GC;F:AGH;E:HD #
Sample output
A B C F G D H E -> 3
开始以为可以取26个大写字母以为有26种,后来看到题目说了最多8个点......没有什么技巧,无脑回溯过了。相同时输出字典序小的
#include<stdio.h> #include<string.h> #include<ctype.h> int n,max,map[26][26],visit[26]; char s[10],s1[10]; //用字符串保存结果待会比较字典序用库函数比较方便 int dfs(int m) {int i,j,min; if (m>=n) {min=0; for (i=0;i<n-1;i++) for (j=i+1;j<n;j++) if ((map[s1[i]-'A'][s1[j]-'A']==1)&&(j-i>min)) min=j-i; if (min<max) {max=min; strcpy(s,s1);} if ((min==max)&&(strcmp(s,s1)>0)) strcpy(s,s1); return 0; } for (i=0;i<26;i++) if (visit[i]==1) {visit[i]=0; s1[m]=i+'A'; dfs(m+1); visit[i]=1; } } int main() {char ch,CH; int i,j; while (scanf("%c",&ch)&&ch!='#') { memset(map,0,sizeof(map)); memset(visit,0,sizeof(visit)); while (scanf("%c",&CH)&&CH!='\n') {if (isalpha(CH)) {map[ch-'A'][CH-'A']=1;map[CH-'A'][ch-'A']=1; visit[ch-'A']=1; visit[CH-'A']=1; } if (CH==';') scanf("%c",&ch); } n=0; max=9999; for (i=0;i<26;i++) if (visit[i]) {s[n]=i+'A'; ++n;} s[n]='\0'; s1[n]='\0'; dfs(0); for (i=0;s[i]!='\0';i++) printf("%c ",s[i]); printf("-> %d\n",max); } return 0; }