Iamtui1010

turnofflights.cpp

Jan 9th, 2022
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include<iostream>
  2. #include<vector>
  3. #include<algorithm>
  4. #include<climits>
  5.  
  6. #define long long long
  7. #define nln '\n'
  8.  
  9. using namespace std;
  10.  
  11. pair<long, long> locate(
  12.     const vector<string> &flr,
  13.     long m, long pst)
  14. {
  15.     long lef, rig;
  16.     if ((long)flr[pst].find('1') == -1)
  17.         lef = m+1, rig = 0;
  18.     else
  19.     {
  20.         lef = flr[pst].find('1');
  21.         string tem = flr[pst];
  22.         reverse(tem.begin(), tem.end());
  23.         rig = m+1-tem.find('1');
  24.     }
  25.     return {lef, rig};
  26. }
  27.  
  28. void visit(
  29.     const vector<string> &flr,
  30.     long pst, long csm, long &ans,
  31.     long fin, long sta, long m)
  32. {
  33.     if (sta <= fin)
  34.     {
  35.         ans = (csm < ans) ? csm : ans;
  36.         return;
  37.     }
  38.     pair<long, long> dtc = locate(flr, m, sta-1);
  39.     string tem = flr[sta-1];
  40.     reverse(tem.begin(), tem.end());
  41.     visit(flr, dtc.first, csm+(m+1-pst)+(m+1-dtc.first)+1, ans, fin, sta-1, m);
  42.     visit(flr, dtc.second, csm+pst+dtc.second+1, ans, fin, sta-1, m);
  43. }
  44.  
  45. int main()
  46. {
  47.     cin.tie(0)->sync_with_stdio(0);
  48.     cout.tie(0)->sync_with_stdio(0);
  49.     // Input
  50.     //freopen("turnofflights.inp", "r", stdin);
  51.     long n, m;     
  52.     cin >> n >> m;
  53.     vector<string> flr(n);
  54.     for (auto &i : flr)
  55.         cin >> i;
  56.     // Process
  57.     // Find lowest floor has light on.
  58.     long sta = n-1, csm = 0;
  59.     while (sta >= 0 && (long)flr[sta].find('1') == -1)
  60.         --sta, ++csm;
  61.     if (sta < 0)
  62.     {
  63.         cout << 0 << nln;
  64.         return 0;
  65.     }
  66.     // Find last floor has light on
  67.     long fin = sta;
  68.     for (long i = 0; i <= sta; ++i)
  69.         if (flr[i].find('1') < flr[i].size())
  70.         {
  71.             fin = i;
  72.             break;
  73.         }
  74.     // Start to turn off light in buildings
  75.     long ans = LLONG_MAX;
  76.     visit(flr, locate(flr, m, sta).second, locate(flr, m, sta).second+csm, ans, fin, sta, m);
  77.     cout << ans << nln;
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment