为什么long long不分写函数会有bug
查看原帖
为什么long long不分写函数会有bug
198547
issacmeng楼主2024/9/1 14:39

如题,这是AC代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vd;
typedef vector<int> vi;
typedef stack<ll> sd;
typedef stack<int> si;
typedef queue<ll> qd;
typedef queue<int> qi;
typedef map<int, int> mii;

int n, a[200010], cnt = 1, seg[200010];
ll ans;

ll f(ll a) { return a * (a + 1) / 2; }

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  if (n == 1)
    cout << "1\n";
  else if (n == 2)
    cout << "3\n";
  else if (n == 3) {
    cin >> a[0] >> a[1] >> a[2];
    if (a[1] - a[0] == a[2] - a[1])
      cout << "6\n";
    else
      cout << "5\n";
  } else {
    cin >> a[1] >> a[2];
    for (int i = 3; i <= n; i++) {
      cin >> a[i];
      if (a[i] - a[i - 1] != a[i - 1] - a[i - 2]) {
        seg[cnt] = i - 1;
        cnt++;
      }
    }
    // for (int i = 1; i < cnt; i++)
    // cout << seg[i] << " ";
    ans = n + f(seg[1] - 1);
    for (int i = 2; i < cnt; i++)
      ans += f(seg[i] - seg[i - 1]);
    ans += f(n - seg[cnt - 1]);
    if (cnt == 1)
      ans = f(n);
    cout << ans << "\n";
  }
  return 0;
}

如果把函数f直接放进主函数里,就有2组数据WA:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vd;
typedef vector<int> vi;
typedef stack<ll> sd;
typedef stack<int> si;
typedef queue<ll> qd;
typedef queue<int> qi;
typedef map<int, int> mii;

int n, a[200010], cnt = 1, seg[200010];
ll ans;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  if (n == 1)
    cout << "1\n";
  else if (n == 2)
    cout << "3\n";
  else if (n == 3) {
    cin >> a[0] >> a[1] >> a[2];
    if (a[1] - a[0] == a[2] - a[1])
      cout << "6\n";
    else
      cout << "5\n";
  } else {
    cin >> a[1] >> a[2];
    for (int i = 3; i <= n; i++) {
      cin >> a[i];
      if (a[i] - a[i - 1] != a[i - 1] - a[i - 2]) {
        seg[cnt] = i - 1;
        cnt++;
      }
    }
    // for (int i = 1; i < cnt; i++)
    // cout << seg[i] << " ";
    ans = n + seg[1] * (seg[1] - 1) / 2;
    for (int i = 2; i < cnt; i++)
      ans += (seg[i] - seg[i - 1] + 1) * (seg[i] - seg[i - 1]) / 2;
    ans += (n - seg[cnt - 1] + 1) * (n - seg[cnt - 1]) / 2;
    if (cnt == 1)
      ans = n * (n + 1) / 2;
    cout << ans << "\n";
  }
  return 0;
}

想请问一下这是为什么?谢谢。

2024/9/1 14:39
加载中...