Codeforces 569B Inventory
2015-08-11 09:18
489 查看
题目链接:
http://codeforces.com/contest/569/problem/B
解题思路:
Let's look at the problem from another side: how many numbers can we leave unchanged to get permutation? It is obvious: these numbers must be from 1 to n and
they are must be pairwise distinct. This condition is necessary and sufficient.
This problem can be solved with greedy algorithm. If me meet the number we have never met before and this number is between 1 and n,
we will leave this number unchanged. To implement this we can use array where we will mark used numbers.
After that we will look over the array again and allocate numbers that weren't used.
Complexity — O(n).
AC代码:
http://codeforces.com/contest/569/problem/B
解题思路:
Let's look at the problem from another side: how many numbers can we leave unchanged to get permutation? It is obvious: these numbers must be from 1 to n and
they are must be pairwise distinct. This condition is necessary and sufficient.
This problem can be solved with greedy algorithm. If me meet the number we have never met before and this number is between 1 and n,
we will leave this number unchanged. To implement this we can use array where we will mark used numbers.
After that we will look over the array again and allocate numbers that weren't used.
Complexity — O(n).
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; int n; int a[100005]; int vis[100005]; int main(){ while(~scanf("%d",&n)){ memset(vis,0,sizeof(vis)); queue<int> q; for(int i = 1; i <= n; i++){ scanf("%d",&a[i]); if(!vis[a[i]] && a[i] <= n) vis[a[i]] = 1; else q.push(i); } int tmp; for(int i = 1; i <= n; i++){ if(!vis[i]){ tmp = q.front(); q.pop(); a[tmp] = i; } } for(int i = 1; i < n; i++) printf("%d ",a[i]); printf("%d\n",a ); } return 0; }
相关文章推荐
- 15-StringBuffer-12-常用对象API(StringBuilder类)
- BZOJ4129: Haruna’s Breakfast
- isis协议第一个Hello包
- js判断上传文件大小 (尝试网上解决方案后结果....)
- 计蒜客 难题题库 222 疲倦程度
- 锂电池的充电电压和电流应该是多少
- A1029. Median (25)
- 变量声明相关
- 时间处理工具类DateUtils
- uiwebview与js交互
- EF 多线程插入 Insert into DbContext Multithreading
- 计蒜客 难题题库 221 N的-2进制表示
- [J2EE]命令行删除、安装tomcat服务器
- 15-StringBuffer-10-常用对象API(StringBuffer类-插入&删除&查找&修改)
- MySQL5.6 新特性之GTID
- Spring+Quartz实现定时任务的配置方法
- BZOJ3289: Mato的文件管理
- HDU4336 Card Collector【容斥原理】
- Android UI 主线程,啥玩意?还有Handler+Looper+MessageQueue几个意思?
- uva 10129 Play On Words(并查集法和DFS法)