您的位置:首页 > 其它

uva 10160 - Servicing Stations

2013-08-08 11:33 246 查看
A company offers personal computers for sale in N towns (3 <= N <= 35). The towns are denoted by 1, 2, ..., N. There are direct routes connecting M pairs from among these towns. The company decides to build servicing stations in several towns, so that for any town X, there would be a station located either in X or in some immediately neighbouring town of X.

Write a program for finding out the minumum number of stations, which the company has to build, so that the above condition holds.

Input
The input consists of more than one description of town (but totally, less than ten descriptions). Every description starts with number N of towns and number M of pairs of towns directly connected each other. The integers N and M are separated by a space. Every one of the next M rows contains a pair of connected towns, one pair per row. The pair consists of two integers for town's numbers, separated by a space. The input ends with N = 0 and M = 0.

Output
For every town in the input write a line containing the obtained minimum.

An example:

Input:

8 12
1 2
1 6
1 8
2 3
2 6
3 4
3 5
4 5
4 7
5 6
6 7
6 8
0 0

Output:

2

题目大意:给你一个无向图,有n个结点,m个边,现在要建立服务站,服务站可以覆盖与它链接的点,问最少需要几个服务站可以覆盖所有结点。

分析:DFS+剪枝,每个结点有选或者不选两种,不剪枝的话就有2^35。我用的是邻接表存储图,因为根据题目意思这样容易枚举每一个点邻接的结点。

注意的是自己到自己是相联通的,这里错了一次。

#include<iostream>
using namespace std;
#include<stdio.h>
#include<string.h>
#define MAXN 40
#define ONE ((long long) 1)
long long st[MAXN], l[MAXN];

bool dfs(int n, long long state, int step, int s, int maxlen)
{
if(state==(ONE<<(n))-1)
return true;  //all the point can be reached
if(step==maxlen)
return false; //all the ways searched, still cann't cover all
if(s>n)
return false;
for(int i=s;i<=n;i++)
{
if((state|l[i])!=(ONE<<(n))-1)
break;
if((state|st[i])==state)
continue;
if(dfs(n,state|st[i],step+1,i+1,maxlen))
return true;
}
return false;
}

int main()
{
int n, m;
while(scanf("%d%d", &n, &m)!=EOF && n+m)
{
long long state=0;
for(int i=1;i<=n;i++)
{
l[i]=0;
st[i]=(ONE<<(i-1));
}
int a, b;
for(int i=1;i<=m;i++)
{
scanf("%d%d", &a, &b);
st[a]|=(ONE<<(b-1));
st[b]|=(ONE<<(a-1));
}
l
=st
;
for(int i=n-1;i>=1;i--)
{
l[i]=st[i]|l[i+1];
}
for(int i=1;i<=n;i++)
{
if(dfs(n,state,0,1,i))
{
printf("%d\n", i);
break;
}
}
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: