a564簡單對角線編號與三角形數

CPE:Can You Solve It? (UVa 10642)

把二維路徑位置轉成單調的一維索引。

前往題目練習 →回報教學錯誤每筆時間 O(1),空間 O(1)。

解題思路

所有 x+y=s 的格點都在同一條對角線,該線共有s+1個點。在它之前的線共有1+2+…+s=s(s+1)/2個點,且本地敘述在同一線從x=0走到x=s,因此 (x,y) 的從零索引為 s(s+1)/2+x。

沿固定方向每走一步索引恰增加1,所以答案直接是 index(終點)−index(起點)。不需要實際枚舉最多數百億個點,也不應把同線偏移寫成y;本題輸入保證能到終點。x、y各可十萬,三角形數需64位元,輸出 Case k: D。

Step-by-step animation

示意:(0,1)走到(1,1)

回報動畫錯誤
步驟 1 / 3

起點索引

s=1,index=1×2/2+0=1。

(0,1):1
起點索引
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

long long indexOf(long long x, long long y) {
    long long s = x + y;
    return s * (s + 1) / 2 + x;
}
int main() {
    int t;
    cin >> t;
    for (int tc = 1; tc <= t; ++tc) {
        long long x, y, a, b;
        cin >> x >> y >> a >> b;
        cout << "Case " << tc << ": " << indexOf(a, b) - indexOf(x, y) << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多