POJ 1129/ZOJ 1084

搜索練習,沒什麼重要的剪枝要考慮,直接按照dfs模板碼就行了!但是網上也有貪心解法,雖然不能確定得到最優解,但是能夠ac!

精確解法代碼如下:

#include <iostream>
#include <vector>
using namespace std;
int n;
vector<vector<int> > adjList;
vector<int> color;
int corNum;
bool Judge(int l, int c)
{
    int i = 0;
    while( i < adjList[l].size() )
    {
	if( c == color[adjList[l][i]] )
	    return false;
	++i;
    }
    return true;
}
bool Dfs(int l)
{
    if( l == n )
	return true;
    for(int i = 1; i <= corNum; ++i)
    {
	if( Judge(l, i) )
	{
	    color[l] = i;
	    if( Dfs(l+1) )
		return true;
	    color[l] = 0;
	}
    }
    return false;
}

int main()
{
    while( cin >> n && n )
    {
	cin.get();
	adjList.clear();
	adjList.resize( n );
	color.assign(n, 0);
	for(int i = 0; i < n; ++i)
	{
	    int u = cin.get() - 'A';
	    cin.get();
	    char ch;
	    while( (ch = cin.get()) != '\n' )
		adjList[u].push_back( ch - 'A' );
	}
	corNum = 1;
	while( !Dfs(0) )
	    ++corNum;
	cout << corNum << " channel";
	cout << ((corNum == 1)?" needed.":"s needed.") << endl;
    }
    return 0;
}

貪心解法(雖然能a,但不是正確解法)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
vector<vector<int> > adjList;
vector<int> color;
int Dfs(int node, int cnt)
{
    if(node == n)
	return cnt;
    vector<bool> c( cnt + 2, false );
    for(int i = 0; i < adjList[node].size(); ++i)
    {
	int v = adjList[node][i];
	c[color[v]] = true;
    }
    int ans = 0xffff;
    for(int i = 1; i <= cnt + 1; ++i)
    {
	if( !c[i] )
	{
	    color[node] = i;
	    int corNum = (i < cnt+1)?cnt:cnt+1;
	    int temp = Dfs(node+1, corNum);
	    ans = min(ans, temp);
	    color[node] = 0;
	}
    }
    return ans;
}
void Work()
{
    int ans = Dfs(0, 0);
    cout << ans << " " ;
    cout << (ans==1?"channel needed.":"channels needed.") << endl;
}

int main()
{
    while( cin >> n && n)
    {
	adjList.clear();
	adjList.resize( n );
	color.assign(n, 0);
	cin.get() ;
	for(int i = 0; i < n; ++i)
	{
	    int s = cin.get() - 'A';
	    cin.get();
	    char ch ;
	    while( (ch = cin.get()) != '\n')
	    {
		adjList[s].push_back( ch - 'A' );
	    }
	}
	/*
	 * first solution : greedy algorithm
	for(int i = 0; i < n; ++i)
	{
	    vector<bool> corSign(n+1, 0);
	    for(int j = 0; j < adjList[i].size(); ++j)
	    {
		int c = color[adjList[i][j]];
		c?corSign[c]=true:NULL;
	    }
	    for(int j = 1; j <= n; ++j)
		if( !corSign[j] )
		{
		    color[i] = j;
		    break;
		}
	}
	int ans = *max_element(color.begin(), color.end());
	cout << ans << " " ;
	cout << (ans==1?"channel needed.":"channels needed.") << endl;
	*/
	/*
	 * 上面那個貪心不能解決http://zhyu.me/acm/poj-1129.html中提到的一個
	 * 例子,下面的dfs和greedy結合貌似可以,但是仍然不能保證得到最優解
	 */
	Work();
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章