Cho dãy n số nguyên dương a1, a2, …, an và số nguyên dương S. Hãy đếm xem có bao nhiêu cặp phần tử (ai, aj) (i <> j) thỏa mãn ai + aj = S.
Input:
· Dòng đầu là số nguyên dương n (n ≤ 106) và s (s ≤ 106)
· N dòng sau, dòng thứ i là số nguyên dương ai (ai≤ 106)
Output: số cặp (ai, aj) thỏa đề bài
Input Output
5 4 3
1 3 1 2 2
Code C++ Subtask full O(N):
Trả lờiXóa#include
using namespace std;
int a[1000006];
int n, s;
long long res=0;
int main() {
freopen("inp.txt", "r", stdin);
freopen("out.txt", "w", stdout);
scanf("%d%d", &n, &s);
for(int i=1; i<=n; i++) {
int x;
scanf("%d" ,&x);
res+=a[s-x], a[x]++;
}
cout << res;
return 0;
}
xin code c++ bạn ơi này là c rồi :v
Xóahaha
Xóaanh em ơi móc lồn nhau đi
Xóaok a ơi
Xóacode hay
Xóamóc lồn đi
Xóabài này test n=9,s=4
Xóamảng: 2 2 2 2 3 3 3 1 1
là sai rồi
và x<0 là sai luôn
Xóacho e xin code bằng pascal
Trả lờiXóaprogram p;
Trả lờiXóauses crt;
var a:array[1..10] of integer;
d,s,n,i:integer;
begin
clrscr;
readln(n,s); d:=0;
for i:=1 to n do readln(a[i]);
for i:=1 to n do
if a[i]+a[i+1]=s then inc(d);
write(d);
readln;
end.
Nhận xét này đã bị tác giả xóa.
XóaUses crt;
Trả lờiXóaVar n,i,j,s,dem:longint;
f,t:array[1..1000000] of longint;
ds:array[1..1000000] of boolean;
Begin
readln(n);
readln(s);
For i:=1 to n do
Begin
readln(f[i]);
t[f[i]]:=t[f[i]]+1;
end;
For i:=1 to n do
If (t[f[i]]>0)and(t[s-f[i]]>0) then
Begin
ds[f[i]]:=true;
ds[s-f[i]]:=true;
end;
For i:=1 to n do
If (ds[f[i]]=true)and(ds[s-f[i]]=true)and(s-f[i]<>f[i]) then
Begin
dem:=dem+t[f[i]]*(t[s-f[i]]);
t[f[i]]:=0;
t[s-f[i]]:=0;
end else If (s-f[i]=f[i]) then
For j:=1 to t[f[i]]-1 do
Begin
dem:=dem+j;
t[f[i]]:=0;
end;
Write(dem);
readln;
end.
Nc
Xóacode c++:
Trả lờiXóa#include
#include
using namespace std;
void findpair(int arr[], int len, int sum)
{
sort(arr, arr+len);
int i = 0;
int j = len -1;
while( i < j){
while((arr[i] + arr[j]) <= sum && i < j)
{
if((arr[i] + arr[j]) == sum)
cout << "(" << arr[i] << "," << arr[j] << ")" << endl;
i++;
}
j--;
while((arr[i] + arr[j]) >= sum && i < j)
{
if((arr[i] + arr[j]) == sum)
cout << "(" << arr[i] << "," << arr[j] << ")" << endl;
j--;
}
}
}
int main(void)
{
int arr [10] = {1,2,3,4,5,6,7,8,9,0};
findpair(arr, 10, 7);
}
len là gì thế ak
XóaCái này chỉ đúng với trường hợp các số trong dãy đôi một khác nhau. Chứ trùng nhau sẽ liệt kê ko hết
Xóa#include
Trả lờiXóausing namespace std;
#define ll long long
int main()
{
ll n, i, s, j, dem=0, max=0, tong;
cin >> n >> s;
ll a[n];
for (i = 0; i < n; i++)
cin >> a[i];
for (i = 0; i < n-1; i++)
for (j = i+1; j < n; j++)
if (a[i]+a[j]==s) dem++;
cout<< dem;
return 0;
}
ngu
Trả lờiXóabọn này ngáo mẹ nó rồi
Trả lờiXóađây là cách trâu bò, m ngu khác del gì
Xóa