Ultraviolet A 10542,

Source: Internet
Author: User

Ultraviolet A 10542,

Link: Ultraviolet A 10542-Hyper-drive

Given a line segment in an n-dimensional space, the line segment goes through several grids.

Solution: For a line segment, you can move one point to the origin point and change it
(0, 0) to (a, B) This line segment, take two-dimensional as an example, each time will move from a grid to another grid, can be x + 1 coordinates, can be y + 1, so the total should be a + b-1, deduct x + 1, y + 1 case gcd (a, B)-1 (origin ). The calculation result of ing to n-dimensional data is calculated using the exclusion principle.

/*********************** * (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;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.