P1102 number of AB

P1102 exam Links: https://www.luogu.org/problem/P1102

1. simple O (n ^ 2) Score 76

All numbers are sequentially input as minuend, the number of outer In addition several other successively as subtrahend, whenever there is a difference between the group is 1, the program number ans + 1

 1 #include <cstdio>
 2 using namespace std;
 3 int main()
 4 {
 5     int n, c, s[200001], ans = 0;
 6     scanf("%d%d", &n, &c);
 7     for(int i = 0; i < n; ++i)
 8         scanf("%d", &s[i]);
 9     for(int i = 0; i < n; ++i)
10     {
11         for(int j = 0; j < n; ++j)
12         {
13             if(i == j) continue;
14             if(s[i] - s[j] == c) ++ans;
15         }
16     }
17     printf("%d\n", ans);
18     return 0;
19 }

 Optimization of the tub 2. O (n) Score 84

Enter a number, the corresponding increase in the tub, because A - B = C -> A - C = B, the possible values ​​for each enumerated A, so that with A - C B is obtained, if A, B is present (i.e., bucket is not 0), the program number ans + = t [A] * t [B]

 1 #include <cstdio>
 2 using namespace std;
 3 int main()
 4 {
 5     int n, c, ans = 0, t[10000001] = {0};
 6     scanf("%d%d", &n, &c);
 7     for(int i = 0; i < n; ++i)
 8     {
 9         int x;
10         scanf("%d", &x);
11         ++t[x];
12     }
13     for(int i = c; i < 10000001; ++i)
14         if(t[i] != 0 && t[i - c] != 0)
15             ans += t[i] * t[i - c];
16     printf("%d\n", ans);
17     return 0;
18 }

3.map optimized AC

 1 #include <cstdio>
 2 #include <map>
 3 using namespace std;
 4 long long a[200001];
 5 map<long long, long long> m;
 6 int main()
 7 {
 8     long long n, c, ans = 0;
 9     scanf("%lld%lld", &n, &c);
10     for(int i = 0; i < n; ++i)
11     {
12         scanf("%lld", &a[i]);
13         ++m[a[i]];
14         a[i] -= c;
15     }
16     for(int i = 0; i < n; ++i)
17         ans += m[a[i]];
18     printf("%lld\n", ans);
19     return 0;
20 }

Guess you like

Origin www.cnblogs.com/ZhangRunqi/p/11286011.html