Bandwidth

来源:互联网 发布:linux怎么ping 编辑:程序博客网 时间:2024/05/17 09:28

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

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

For these orderings, the bandwidths of thenodes (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 orderingof 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 terminatedby a line consisting of a single #. For each graph, theinput will consist of a series of records separated by `;'. Each record willconsist 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 willcontain no more than 8 nodes.

Output

Output will consist of one line for eachgraph, listing the ordering of the nodes followed by an arrow (->) and thebandwidth for that ordering. All items must be separated from their neighboursby exactly one space. If more than one ordering produces the same bandwidth,then choose the smallest in lexicographic ordering, that is the one that wouldappear 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

这道题主要是如何把输入的数据存储。Liu用的是“指针”来标记位置,放到vector里面,而且用的是两个vector,更加直观。另外,此题应用数组进行了很多转化:一是用id【】把字母转化成连续的数字,用letter【】把数字和相应的字母联系起来,可见可以使用两个数组把字母和数字给联系起来;二是用pos【】来记录字母的位置。代码如下:

#include<cstdio>#include<cmath>#include<vector>#include<cstring>#include<algorithm>using namespace std;const int maxn=1000+5;char letter[maxn];int id[maxn],pos[maxn];int main(){//freopen("in.in","r",stdin);char s[maxn];while(scanf("%s",s)==1&&s[0]!='#'){int n=0;for(int i='A';i<='Z';i++){if(strchr(s,i)!=NULL){   //巧用strchr避免重复的字母,直接记录字母的个数id[i]=n++;letter[id[i]]=i;}}vector<int> u,v;int p=0,q=0;for(;;){while(p<strlen(s)&&s[p]!=':') p++;if(p==strlen(s)) break;while(q<strlen(s)&&s[q]!=';') q++;for(int i=p+1;i<q;i++){u.push_back(id[s[p-1]]);v.push_back(id[s[i]]);}p++;q++;}int P[maxn],ans=n,bestp[maxn];for(int i=0;i<n;i++) P[i]=i;do{int big=0;for(int i=0;i<n;i++) pos[P[i]]=i;for(int i=0;i<u.size();i++){big=max(big,abs(pos[u[i]]-pos[v[i]]));}if(big<ans){ans=big;memcpy(bestp,P,sizeof(P));   //memcpy复制任意类型的串}}while(next_permutation(P,P+n));  //用next_permutation实现全排列for(int i=0;i<n;i++){printf("%c ",letter[bestp[i]]);}printf("-> %d\n",ans);}//fclose(stdin);return 0;}


0 0
原创粉丝点击