uva 140 Bandwidth(全排列+递归)

快睡觉的时候1A的大笑把序列全排列,递归暴力判断就ok啦,我改成对应的整数存了,a数组存的是所有的字符的排列,

b数组存的是所有开始节点的排列,map[i][j]数组存的是i为起点,与j相邻

贴代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<limits.h>
#include<math.h>
#include<algorithm>
using namespace std;
int map[10][30];
int a[30];
int b[10];
int visit[30];
int Min,s,Max2;
int ma[30];
int cmp(const void *c,const void *d)
{
	return *(int *)c - *(int *)d;
}
void dfs(int x,int y)
{
	int Max1 = 0;
	for(int i=0; i<s; i++)
	{
		if(map[x][a[i]] == 1)
		{
			if(abs(y-i) > Max1)
				Max1 = abs(y-i);
		}
	}
	if(Max1 > Max2)
		Max2 = Max1;
	return ;
}
int main()
{
	char ch;
	int i,j,flag = 1,k=0;
	s = 0;
	Min = INT_MAX;
	memset(a,0,sizeof(a));
	memset(b,0,sizeof(b));
	memset(visit,0,sizeof(visit));
	memset(map,0,sizeof(map));
	while(scanf("%c",&ch),ch!='#')
	{
		if(ch >= 'A' && ch <= 'Z' && (visit[ch-'A'] == 0))
		{
			visit[ch - 'A'] = 1;
			a[s++] = ch - 'A'; 
		}
		if(ch >= 'A' && ch <= 'Z' && (flag == 1))
			{
			    i = ch - 'A';
			    b[k++] = i;
			}
		else if(ch >= 'A' && ch <= 'Z' && (flag == 0))
			map[i][ch-'A'] = 1;
		else if(ch == ':')
			flag = 0;
		else if(ch == ';')
		{
			flag = 1;
			continue;
		}
		else if(ch == '\n')
		{
			qsort(a,s,sizeof(a[0]),cmp);
			do
			{
				Max2 = 0;
				for(i=0; i<s; i++)
				{
					for(j=0; j<k; j++)
					{
						if(a[i] == b[j])
							dfs(a[i],i);
					}
				}	
				if(Max2 < Min)
					{
						Min = Max2;
						for(int p=0; p<s; p++)
						{
							ma[p] = a[p];
						}
					}
			}while(next_permutation(a,a+s));
			for(i=0; i<s; i++)
				printf("%c ",ma[i]+'A');
				printf("-> ");
			printf("%d\n",Min);
				memset(a,0,sizeof(a));
				memset(b,0,sizeof(b));
				memset(visit,0,sizeof(visit));
				memset(map,0,sizeof(map));
				s = k = 0;
				flag = 1;
				Min = INT_MAX;
		}
		
	}
	return 0;
} 


你可能感兴趣的:(uva 140 Bandwidth(全排列+递归))