您的位置:首页 > 其它

USACO holstein, hamming

2011-07-10 15:25 239 查看
微博: http://t.sina.com.cn/g7tianyi
豆瓣:http://www.douban.com/people/Jackierasy/
广度优先搜索的好题,广搜的好处之一就是往往可以直接找到最短路径,而且,就本题而言,还可以大规模剪枝。
优化的话估计还可以用位运算,那样最后一组数据应该也可以在0s内AC掉。



/*
ID: fairyroad
TASK:holstein
LANG:C++
*/
//#define DEBUG
#include<deque>
#include<fstream>
#include<iostream>
using namespace std;
ifstream fin("holstein.in");
ofstream fout("holstein.out");

typedef deque<int> Queue;
int V, G;
int vitamin[25];
int fertilizer[15][25];
struct node
{
Queue currsum, path;
node() : currsum(0), path(0) {}
node(const deque<int>& cs, const deque<int>& p) : currsum(cs), path(p) {}
};

#ifdef DEBUG
inline void printnode(const node& nd)
{
cout<<"currsum :  ";
for(size_t i = 0; i < nd.currsum.size(); ++i) cout<<nd.currsum[i]<<' ';
cout<<"\npath :  ";
for(size_t i = 0; i < nd.path.size(); ++i) cout<<nd.path[i]<<' ';
cout<<"\n";
}
#endif

inline bool check(const Queue& sum)
{
for(int i = 0; i < V; ++i)
if(sum[i] < vitamin[i]) return false;

return true;
}

inline void addi(Queue& sum, int index)
{
for(size_t i = 0; i < sum.size(); ++i)
sum[i]+=fertilizer[index][i];
}

int main()
{
fin>>V;
for(int i = 0; i < V; ++i) fin>>vitamin[i];
fin>>G;
for(int i = 0; i < G; ++i)
for(int j = 0; j < V; ++j)
fin>>fertilizer[i][j];

deque<node> Q;
Queue start_sum(V,0), start_path;
//start_sum.push_back(0);
start_path.push_back(-1); // for initilization, don't fell wierd
Q.push_back(node(start_sum, start_path));
while(!Q.empty())
{
node n = Q.front();
#ifdef DEBUG
printnode(n);
#endif

for(int i = n.path.back()+1; i < G; ++i)
{
Queue tmpsum(n.currsum), tmppath(n.path);
addi(tmpsum, i);
tmppath.push_back(i);
if(check(tmpsum))
{
fout<<tmppath.size()-1<<' ';
for(size_t j = 1; j < tmppath.size()-1; ++j)
fout<<tmppath[j]+1<<' ';
fout<<i+1 <<"\n";
goto DONE;
}
Q.push_back(node(tmpsum, tmppath));
}
Q.pop_front();
}

DONE:
return 0;
}


hamming是水题,USACO对位运算的考察还是很全面的。但是位运算是基础。



/*
ID: fairyroad
TASK:hamming
LANG:C++
*/

#include<fstream>
using namespace std;
ifstream fin("hamming.in");
ofstream fout("hamming.out");

int N, B, D;
int res[64];
// return the number of 1 in the binary representation of the xor of a and b
inline int counthd(int a, int b)
{
int count = 0, n = a^b;
while(n)
{
n &= (n-1);
++count;
}
return count;
}

int main()
{
fin>>N>>B>>D;
int num = 1;
for(int i = 1; num <= N && i <= (1<<B)-1; ++i)
{
bool flag = true;
for(int j = 0; j < num; ++j)
if(counthd(res[j], i) < D)
{
flag = false;
break;
}
if(flag) res[num++] = i;
}

// output
for (int i=0; i<N-1; i++) fout<<res[i]<<( ((i+1)%10==0)?"\n":" ");
fout<<res[N-1]<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: