题解:P13404 [GCJ 2010 #3] Fence
JiuZhE66666 · · 题解
结合原版题解和自己的想法...
首先看题
贪心的想法是:栅栏这么长,肯定要优先使用最长的木板。
-
设所有木板中,最长的长度为
A 。 -
总长度
L 可以表示为L = p \times A + q ,其中p = \left\lfloor \frac{L}{A} \right\rfloor 是我们打算使用的A 型木板的数量,q = L \bmod A 用其他木板凑。 -
我们天真地希望用
p 块A 型木板,然后用其他木板凑出长度q ,但这不一定存在方案。也许我们少用一块A 型木板,即用p-1 块,然后去凑A+q ,反而可以凑出来。- 方案 1:用
p 块A 型木板和T_0 块其他木板凑q 。总数p + T_0 。 - 方案 2:用
p-1 块A 型木板和T_1 块其他木板凑A+q 。总数(p-1) + T_1 。 - 方案
i :用p - i 块A 型木板和T_i 块其他木板凑i \times A + q 。总数(p - i) + T_i 。
- 方案 1:用
关键观察
- 在所有可行方案中,最优的方案对应使
T_i - i 最小的那个i ,因为T_i 增长得比i 更快。 - 每个可行方案里,其他木板凑出的总长度对
A 取模的余数一定是q ,即i\times A + q \equiv q \pmod A.
题解
以上思路告诉我们:只需在所有其他木板的组合中,找到能够拼出与
code
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll INF=1e18;
void solve(int cs)
{
ll len;
ll n;
cin>>len>>n;
vector<ll>blocks(n);
ll mx=0;
for(int i=0;i<n;++i)
{
cin>>blocks[i];
if(blocks[i]>mx)
mx=blocks[i];
}
if(mx==0)
{
cout<<"Case #"<<cs<<": ";
if(len==0)
{
cout<<0<<"\n";
}
else
{
cout<<"IMPOSSIBLE\n";
}
return;
}
vector<ll>dist(mx,INF);
vector<bool>inq(mx,false);
queue<ll>q;
dist[0]=0;
q.push(0);
inq[0]=true;
while(!q.empty())
{
ll u=q.front();
q.pop();
inq[u]=false;
for(ll b:blocks)
{
ll v=(u+b)%mx;
ll w=1LL-(u+b)/mx;
if(dist[u]!=INF&&dist[u]+w<dist[v])
{
dist[v]=dist[u]+w;
if(!inq[v])
{
q.push(v);
inq[v]=true;
}
}
}
}
ll p=len/mx;
ll rem=len%mx;
cout<<"Case #"<<cs<<": ";
if(dist[rem]==INF)
{
cout<<"IMPOSSIBLE\n";
}
else
{
ll ans=p+dist[rem];
cout<<ans<<"\n";
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int T;
cin>>T;
for(int i=1;i<=T;++i)
solve(i);
return 0;
}