codeforces croc 2016 C. Enduring Exodus
题目链接 题意:给出n和k,给出一个长度为n的字符串表示房间的占用情况(0表示没占用,1表示已占用),从n个房间中找出k+1个,使得k+1中的k个距离k+1个中的1个的距离和最小。
思路:只需要考虑没被占用的位置。所以用pos[]数组记录0的位置。 找到第一个能住下的位置后向前平移即可。
1/* ***********************************************
2Author :111qqz
3Created Time :2016年03月19日 星期六 00时21分28秒
4File Name :code/cf/croc2016/C.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=1E5+7;
34int ban[N];
35int k,n;
36int sum[N];
37int pos0[N];
38string st;
39
40int dis(int x,int l,int r)
41{
42 return max(pos0[x]-pos0[l],pos0[r]-pos0[x]);
43}
44int main()
45{
46 #ifndef ONLINE_JUDGE
47 freopen("code/in.txt","r",stdin);
48 #endif
49 cin>>n>>k;
50 cin>>st;
51 ms(ban,0);
52 ms(pos0,0);
53 k++;
54 int len = st.length();
55 int cnt0 = 0;
56 for ( int i = 0 ; i < len ; i++)
57 {
58 if (st[i]=='0')
59 {
60 ban[i+1] = 0;
61 cnt0++;
62 pos0[cnt0] = i ;
63 }
64 else
65 {
66 ban[i+1] = 1;
67 }
68 }
69
70 sum[0] = 0 ;
71
72 for ( int i = 1 ; i <= n ; i++)
73 {
74 sum[i] = sum[i-1] + ban[i];
75 }
76 int ans = inf;
77 int l = 1 ; int r = k;
78 int mid = 0;
79 for ( int i = 1 ; i <= r ; i++)
80 {
81 if (dis(i,l,r)<dis(mid,l,r))
82 {
83 mid = i;
84 }
85 }
86
87 ans = dis(mid,l,r);
88 for ( ; r <= cnt0 ; r++,l++)
89 {
90 while (dis(mid+1,l,r)<dis(mid,l,r)) mid++;
91 ans = min(ans,dis(mid,l,r));
92 }
93 cout<<ans<<endl;
94
95
96
97
98
99 #ifndef ONLINE_JUDGE
100 fclose(stdin);
101 #endif
102 return 0;
103}