搜索策略
传送门 我们发现:一共有1000点*1000个结果,我们就将这个作为搜索的状态进行记录,这样是不会TLE的
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N=1010;
int n,m,ans;
vector<pii> G[N];
bool vis[N*2][N];
queue<pii> q;
pii cur,nxt;
void bfs(){
q.push({0,1});
vis[0][1] = true;
while(!q.empty()){
cur = q.front();
int pl = cur.second;
q.pop();
if(pl == n) ans = min(ans,cur.first);
for(auto v:G[pl]){
int x = v.second;
int val = v.first^cur.first;
if(vis[val][x]) continue;
vis[val][x] = true;
q.push({val,x});
}
}
}
signed main(){
cin>>n>>m;
for(int i=1;i<=m;i++){
int a,b,w;
cin>>a>>b>>w;
G[a].push_back({w,b});
}
ans = 0x3f3f3f3f;
bfs();
if(ans == 0x3f3f3f3f) ans = -1;
cout<<ans<<"\n";
return 0;
}诈骗
1.搜索、暴力 传送门
如果直接广搜,我们会觉得复杂度是1e5 * 1e5 * 1e5 = 1e15
之后发现:水的总量不变,这样C中水量可以用all - A - B表示,复杂度1e5 * 1e5 = 1e10
最后,我们又发现:进行一次操作后,水量只会有一下两种情况:
1.有一个瓶子是空的,另外两个总和不变。有三个瓶子可以空,共3 * 1e5
2.有一个瓶子是满的,另外两个总和不变。有三个瓶子可以空,共3 * 1e5
所以总复杂度6e5,直接广搜可以过
自己写广搜写死了,给AI调差点给它调崩溃了,奇耻大乳。。。给出AI代码
Code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_C = 100000;
const ll inf = 0x3f3f3f3f3f3f3f3f;
int A, B, C, a, b, c, total;
ll ans[MAX_C + 10];
unordered_map<ll, int> dist;
// 编码状态(x,y)为long long
inline ll encode(int x, int y) {
return 1LL * x * (B + 1) + y;
}
// 更新答案数组
void update_ans(int x, int y, int steps) {
int z = total - x - y;
if (x <= MAX_C) {
if (ans[x] < 0 || steps < ans[x]) ans[x] = steps;
}
if (y <= MAX_C) {
if (ans[y] < 0 || steps < ans[y]) ans[y] = steps;
}
if (z >= 0 && z <= MAX_C) {
if (ans[z] < 0 || steps < ans[z]) ans[z] = steps;
}
}
int main() {
freopen("juice.in","r",stdin);
freopen("juice.out","w",stdout);
// 输入
cin >> A >> B >> C;
cin >> a >> b >> c;
total = a + b + c;
// 初始化答案数组为-1
memset(ans, -1, sizeof(ans));
queue<pair<int, int>> q;
// 初始状态
dist[encode(a, b)] = 0;
q.push({a, b});
update_ans(a, b, 0);
while (!q.empty()) {
auto cur = q.front(); q.pop();
int x = cur.first, y = cur.second;
int steps = dist[encode(x, y)];
int z = total - x - y;
// 定义6种移动操作
vector<tuple<int, int, int>> moves = {
// 从x倒入y
{min(x, B - y), x - min(x, B - y), y + min(x, B - y)},
// 从y倒入x
{min(y, A - x), x + min(y, A - x), y - min(y, A - x)},
// 从x倒入z(仅更新x)
{min(x, C - z), x - min(x, C - z), y},
// 从z倒入x(仅更新x)
{min(z, A - x), x + min(z, A - x), y},
// 从y倒入z(仅更新y)
{min(y, C - z), x, y - min(y, C - z)},
// 从z倒入y(仅更新y)
{min(z, B - y), x, y + min(z, B - y)}
};
for (auto [pour, nx, ny] : moves) {
if (pour == 0) continue; // 跳过无效移动
ll key = encode(nx, ny);
// 新状态未访问或找到更短路径
if (dist.find(key) == dist.end() || steps + 1 < dist[key]) {
dist[key] = steps + 1;
q.push({nx, ny});
update_ans(nx, ny, steps + 1);
}
}
}
// 输出结果(0到C)
for (int i = 0; i <= C; i++) {
cout << ans[i];
if (i < C) cout << " ";
}
return 0;
}分治法
可以尝试将区间问题转化成左右区间的合并这样可以log层地递归