uva 10542,

來源:互聯網
上載者:User

uva 10542,

題目連結:uva 10542 - Hyper-drive

題目大意:給定n維空間的線段,問說線段經過幾個格子。

解題思路:對於線段可以將一點移動至原點,變成
(0,0)到(a,b)這條線段,以二維為例,每次會從一個格子移動到另一個格子,可以是x+1座標,也可以是y+1,所以總的應該是a+b-1,扣除掉x+1,y+1的情況gcd(a,b)-1 (原點)。映射成n維就要用容斥原理計算結果。

/*********************** * (0, 0, 0, ...) -> (a, b, c, ...) * ans = a + b + c +.. - gcd(a,b) - gcd(a,c) - .. + gcd(a, b, c) ...***********************/#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 15;int N, d[maxn], g[2][maxn];inline int gcd (int a, int b) {    return b == 0 ? a : gcd (b, a%b);}void init () {    scanf("%d", &N);    for (int i = 0; i < 2; i++)        for (int j = 0; j < N; j++)            scanf("%d", &g[i][j]);    for (int i = 0; i < N; i++)        d[i] = abs(g[0][i] - g[1][i]);}ll solve () {    ll ans = 0;    for (int i = 1; i < (1<<N); i++) {        int sign = -1, tmp = -1;        for (int j = 0; j < N; j++) {            if (i&(1<<j)) {                tmp = (tmp == -1 ? d[j] : gcd(tmp, d[j]));                sign *= -1;            }        }        ans += tmp * sign;    }    return ans;}int main () {    int cas;    scanf("%d", &cas);    for (int i = 1; i <= cas; i++) {        init();        printf("Case %d: %lld\n", i, solve());    }    return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.