G - 7 POJ - 3414
BFS算法
#include <iostream>
#include <queue>
using namespace std;
int *color;
int *pi;
int *d;
int *operation; //保存操作
int BFS(int A, int B, int C)
{
if (C == 0)
return 0;
int num[2] = { A,B };
int temp = (A + 1)*(B + 1); //二维数组元素个数
color = new int[temp];
pi = new int[temp];
d = new int[temp];
operation = new int[temp];
for (int i = 0; i < temp; i++) //初始化
{
color[i] = 0;
pi[i] = 0;
d[i] = 0;
operation[i] = 0;
}
color[0] = 1; //(0,0)
d[0] = 0;
queue<int> Q;
Q.push(0);
while (!Q.empty())
{
int u = Q.front();
Q.pop();
int v[2];
v[0] = u / (B + 1); //瓶A中的水容量
v[1] = u - v[0] * (B + 1); //瓶B中的水容量
int i; //经过操作后,新的容量(i/(B+1),i%(B+1))
for (int j = 0; j < 6; j++)
{
switch (j)
{
case 0:
i = num[0] * (B + 1) + v[1]; //FILL(1)
break;
case 1:
i = v[0] * (B + 1) + num[1]; //FILL(2)
break;
case 2:
i = v[1]; //DROP(1)
break;
case 3:
i = v[0] * (B + 1); //DROP(2)
break;
case 4:
if (v[0] + v[1] <= num[0])
i = (v[0] + v[1])*(B + 1);
else
i = (num[0] * (B + 1)) + v[1] - (num[0] - v[0]);
break; //POUR(2,1)
case 5:
if (v[0] + v[1] <= num[1])
i = (v[0] + v[1]);
else
i = (v[0] - (num[1] - v[1]))*(B + 1) + num[1];
break; //POUR(1,2)
default:
break;
}
if (color[i] == 0)
{
d[i] = d[u] + 1;
color[i] = 1;
pi[i] = u;
operation[i] = j;
if (i / (B + 1) == C || (i % (B + 1)) == C)
return i;
Q.push(i);
}
}
color[u] = 2;
}
return -1;
}
void print_path(int s, int v) //输出路径
{
if (v == s)
return;
print_path(s, pi[v]);
switch (operation[v])
{
case 0:
cout << "FILL(1)";
break;
case 1:
cout << "FILL(2)";
break;
case 2:
cout << "DROP(1)";
break;
case 3:
cout << "DROP(2)";
break;
case 4:
cout << "POUR(2,1)";
break;
case 5:
cout << "POUR(1,2)";
break;
default:
break;
}
cout << endl;
}
int main()
{
int A, B, C;
cin >> A >> B >> C;
int output = BFS(A, B, C); //搜索
if (output != -1)
{
cout << d[output] << endl; //输出操作次数
print_path(0, output); //输出操作步骤
}
else
cout << "impossible" << endl;
}
I - 9 UVA - 424
高精度算法
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
int p[100][200];
int ans[200];
for (int i = 0; i < 200; ++i)
{
ans[i] = 0;
}
for (int i = 0; i < 100; ++i)
{
for (int t = 0; t < 200; ++t)
{
p[i][t] = 0;
}
}
char *input = NULL;
input = new char[100];
for (int i = 0; i < 100; ++i)
{
input[i] = '0';
}
int line=0;
while (cin >> input, input[0] != '0')
{
int y = strlen(input);
// cout << "y=strlen(input)=" << y<<endl;
for (int i = y-1,t=199; i>=0 ; --i,--t)
{
p[line][t] = input[i]-'0';
}
++line;
}
// cout << line<<endl;
/* for (int i = 0; i < line; ++i)
{
for (int t = 0; t < 200; ++t)
{
cout<<p[i][t];
}
cout << endl;
}*/
for (int i = 199; i >0; --i)
{
for (int t = 0; t < line; ++t)
{
ans[i] += p[t][i];
}
if (ans[i] >= 10)
{
ans[i - 1] += (ans[i] / 10);
ans[i] = ans[i] % 10;
}
}
int k;
for (int i = 1; i <= 200; ++i)
{
if (ans[i] == 0)
{
k = i;
}
else break;
}
for (int i = k+1; i < 200; ++i)
{
cout << ans[i];
}
}
ps:计算结果是正确的,不知为何ac不了