[CC-INVENTRY]Arranging the Inventory

题目大意:

有一排长度为\(n(\sum n\le10^6)\)的格子,有些格子是空的,有些格子上有一个箱子。 现在你要用最小的操作把箱子都移到最左边。

每次可以进行下列两种操作:

  1. 如果第\(i,i+2\)格为空,第\(i+1\)格有箱子,则可以站在第\(i+2\)格将箱子向左推一格(.#.\(\to\)#..
  2. 如果第\(i+1,i+2\)格为空,第\(i\)格有箱子,则可以站在第\(i+1\)格将箱子向右拉一格(#..\(\to\).#.

输出最小的步数或说明无解。

思路:

除了已经在最左端的部分,对于一段连续的#。显然要先将其展开成#.#.#.#.的形式,然后才能往左推。\(\mathcal O(n)\)模拟即可。

源代码:

#include<queue>
#include<cstdio>
#include<cctype>
#include<cstring>
inline int getint() {
register char ch;
while(!isdigit(ch=getchar()));
register int x=ch^'0';
while(isdigit(ch=getchar())) x=(((x<<2)+x)<<1)+(ch^'0');
return x;
}
inline bool check(const char &ch) {
return ch=='.'||ch=='#';
}
inline bool getval() {
register char ch;
while(!check(ch=getchar()));
return ch=='#';
}
typedef long long int64;
const int N=1e5+1;
int p[N];
int main() {
for(register int T=getint();T;T--) {
const int n=getint();
int m=0;
for(register int i=1;i<=n;i++) {
if(getval()) p[++m]=i;
}
int64 ans=0;
int q;
for(q=1;p[q]==q;q++);
for(register int i=q;i<=m;i++) {
if(p[i-1]+2>p[i]) {
ans+=p[i-1]+2-p[i];
p[i]=p[i-1]+2;
}
ans+=p[i]-i;
}
if(q<=n&&p[m]>=n) {
puts("-1");
continue;
}
printf("%lld\n",ans);
}
return 0;
}

最新文章

  1. js confirm函数 删除提示
  2. js中的prototype和constructor
  3. 父视图 使用 UIViewAnimationWithBlocks 时,如何让子视图无动画
  4. php empty()和isset()的区别&lt;转载&gt;
  5. vc 在edit控件中动态插入数据滚动显示
  6. GIT问题,error:src refspec master does not match any
  7. Flume-ng源码解析之Source组件
  8. 视频加载logo 2
  9. Mysql修改已有数据的字符集
  10. Hazelcast分布式
  11. [LeetCode] Advantage Shuffle 优势洗牌
  12. Oracle day05 索引_数据去重
  13. Linux基础命令---ipcs显示进程通信
  14. 【Alpha】测试报告
  15. hdu—3861(tarjan+二分图)
  16. &#39;tensorflow&#39; has no attribute &#39;sub&#39;
  17. facebook工具xhprof的安装与使用-分析php执行性能
  18. BZOJ4891:[TJOI2017]龙舟(Pollard-Rho,exgcd)
  19. LOJ P3953 逛公园 NOIP dp 最短路 拓扑排序
  20. 模块讲解----hashlib模块(加密)

热门文章

  1. Java+selenium之WebDriver模拟鼠标键盘操作(六)
  2. Linux发布WebApi
  3. Swap file &quot;.hive-site.xml.swp&quot; already exists
  4. Jhipster Registry(Eureka Server) Docker双向联通与高可用部署
  5. mySql中SUBSTRING_INDEX函数用法
  6. ifconf家族命令
  7. javascript功能插件大集合,写前端的亲们记得收藏
  8. Codeforces 980E The Number Games 贪心 倍增表
  9. P1012 拼数 字符串
  10. scrapy 日志一般配置